package database

import (
	"context"
	"database/sql"
	"fmt"
	"regexp"
	"strconv"
	"strings"
	"time"

	"github.com/pkg/errors"
	"gorm.io/gorm"
	"gorm.io/gorm/callbacks"
	"gorm.io/gorm/clause"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/migrator"
	"gorm.io/gorm/schema"

	"changeme/internal/models"

	// Import the DM driver
	_ "gitee.com/chunanyong/dm"
)

// DaMengDialector 达梦方言实现
type DaMengDialector struct {
	DSN  string
	Conn *sql.DB
}

// Name 返回方言名称
func (dialector DaMengDialector) Name() string {
	return "dameng"
}

// Initialize 初始化连接
func (dialector DaMengDialector) Initialize(db *gorm.DB) (err error) {
	// Create callbacks for GORM
	callbacks.RegisterDefaultCallbacks(db, &callbacks.Config{
		LastInsertIDReversed: true,
	})

	if dialector.Conn != nil {
		db.ConnPool = dialector.Conn
	} else if dialector.DSN != "" {
		conn, err := sql.Open("dm", dialector.DSN)
		if err != nil {
			return errors.Wrap(err, "failed to open DaMeng connection")
		}

		// 设置连接池参数
		conn.SetMaxOpenConns(25)
		conn.SetMaxIdleConns(5)
		conn.SetConnMaxLifetime(5 * time.Minute)

		db.ConnPool = conn
	}

	// 注册自定义字句处理器
	db.ClauseBuilders["LIMIT"] = buildLimitClause

	return nil
}

// buildLimitClause 自定义LIMIT语句构建器
func buildLimitClause(c clause.Clause, builder clause.Builder) {
	if limit, ok := c.Expression.(clause.Limit); ok {
		if limit.Limit != nil && *limit.Limit > 0 {
			builder.WriteString("FETCH FIRST ")
			builder.WriteString(strconv.Itoa(int(*limit.Limit)))
			builder.WriteString(" ROWS ONLY")
		}
		if limit.Offset > 0 {
			builder.WriteString(" OFFSET ")
			builder.WriteString(strconv.Itoa(int(limit.Offset)))
			builder.WriteString(" ROWS")
		}
	}
}

// Migrator 返回迁移器
func (dialector DaMengDialector) Migrator(db *gorm.DB) gorm.Migrator {
	return &DaMengMigrator{
		Migrator: migrator.Migrator{
			Config: migrator.Config{
				DB:                          db,
				Dialector:                   dialector,
				CreateIndexAfterCreateTable: true,
			},
		},
	}
}

// DaMengMigrator 达梦迁移器实现
type DaMengMigrator struct {
	migrator.Migrator
}

// DataTypeOf 获取字段数据类型
func (dialector DaMengDialector) DataTypeOf(field *schema.Field) string {
	switch field.DataType {
	case schema.Bool:
		return "NUMBER(1)"
	case schema.Int, schema.Uint:
		// 处理自增主键
		if field.AutoIncrement {
			return "IDENTITY"
		}
		return "INTEGER"
	case schema.Float:
		return "NUMBER"
	case schema.String:
		size := field.Size
		if size == 0 {
			size = 255
		}
		if size > 4000 {
			return "CLOB"
		}
		return fmt.Sprintf("VARCHAR(%d)", size)
	case schema.Time:
		return "TIMESTAMP"
	case schema.Bytes:
		return "BLOB"
	}
	return ""
}

// DefaultValueOf 获取字段默认值
func (dialector DaMengDialector) DefaultValueOf(field *schema.Field) clause.Expression {
	return clause.Expr{SQL: field.DefaultValue}
}

// BindVarTo 转换绑定变量
func (dialector DaMengDialector) BindVarTo(writer clause.Writer, stmt *gorm.Statement, v interface{}) {
	writer.WriteByte('?')
}

// QuoteTo 转义标识符
func (dialector DaMengDialector) QuoteTo(writer clause.Writer, str string) {
	writer.WriteByte('"')
	writer.WriteString(str)
	writer.WriteByte('"')
}

// Explain SQL解释
func (dialector DaMengDialector) Explain(sql string, vars ...interface{}) string {
	return logger.ExplainSQL(sql, nil, `'`, vars...)
}

// DaMengDriver 达梦数据库驱动
type DaMengDriver struct {
	BaseDriver
	gormDB           *gorm.DB
	capabilities     DatabaseCapabilities
	charsetInfo      *CharsetInfo // 缓存的字符集信息
	isByteSemantics  *bool        // 缓存的字符语义设置
	charsetCacheTime time.Time    // 缓存时间
}

// NewDaMengDriver 创建达梦驱动实例
func NewDaMengDriver() *DaMengDriver {
	return &DaMengDriver{
		BaseDriver: BaseDriver{
			Dialect: &DaMengDialect{},
		},
		capabilities: &DaMengCapabilities{},
	}
}

// DaMengDialect 达梦SQL方言
type DaMengDialect struct{}

func (d *DaMengDialect) QuoteIdentifier(identifier string) string {
	return `"` + strings.ReplaceAll(identifier, `"`, `""`) + `"`
}

func (d *DaMengDialect) QuoteString(str string) string {
	return "'" + strings.ReplaceAll(str, "'", "''") + "'"
}

func (d *DaMengDialect) GetDataTypeMapping() map[string]string {
	return map[string]string{
		"varchar":   "VARCHAR",
		"varchar2":  "VARCHAR2",
		"char":      "CHAR",
		"clob":      "CLOB",
		"int":       "INT",
		"integer":   "INTEGER",
		"number":    "NUMBER",
		"decimal":   "DECIMAL",
		"float":     "FLOAT",
		"double":    "DOUBLE",
		"date":      "DATE",
		"time":      "TIME",
		"timestamp": "TIMESTAMP",
		"blob":      "BLOB",
		"binary":    "BINARY",
		"boolean":   "BOOLEAN",
	}
}

func (d *DaMengDialect) GetLimitClause(limit, offset int) string {
	if offset > 0 {
		// 使用ROWNUM实现分页
		return fmt.Sprintf("OFFSET %d ROWS FETCH NEXT %d ROWS ONLY", offset, limit)
	}
	return fmt.Sprintf("FETCH FIRST %d ROWS ONLY", limit)
}

func (d *DaMengDialect) GetCurrentTimeFunction() string {
	return "SYSTIMESTAMP"
}

func (d *DaMengDialect) GetAutoIncrementClause() string {
	return "IDENTITY"
}

// 临时结构体定义，用于表示查询结果
type tableResult struct {
	Name       string `gorm:"column:name"`
	SchemaName string `gorm:"column:schema_name"`
	Type       string `gorm:"column:type"`
	Engine     string `gorm:"column:engine"`
	Comment    string `gorm:"column:comment"`
}

// columnResult 表示查询结果中的列信息
type columnResult struct {
	Name          string `gorm:"column:column_name"`
	Type          string `gorm:"column:data_type"`
	Length        int64  `gorm:"column:data_length"`
	Precision     *int   `gorm:"column:data_precision"`
	Scale         *int   `gorm:"column:data_scale"`
	IsNullable    int    `gorm:"column:nullable"`
	Position      int    `gorm:"column:column_id"`
	DefaultValue  string `gorm:"column:default_value"`
	Comment       string `gorm:"column:comment"`
	CharSemantics string `gorm:"column:char_semantics"` // 新增：字符语义
}

type indexResult struct {
	Name       string `gorm:"column:name"`
	Uniqueness string `gorm:"column:uniqueness"`
	Type       string `gorm:"column:index_type"`
	Status     string `gorm:"column:status"`
}

type indexColumnResult struct {
	IndexName      string `gorm:"column:index_name"`
	ColumnName     string `gorm:"column:column_name"`
	ColumnPosition int    `gorm:"column:column_position"`
}

// Connect 连接到达梦数据库
func (d *DaMengDriver) Connect(config *models.DatabaseConfig) error {
	if d.Connected {
		return ErrConnectionExists
	}

	// 构建达梦连接字符串
	dsn := fmt.Sprintf("dm://%s:%s@%s:%d",
		config.Username, config.Password, config.Host, config.Port)

	// 添加数据库名称（如果提供）
	if config.Database != "" {
		dsn += "/" + config.Database
	}

	// 添加其他参数
	var params []string
	if config.Charset != "" {
		params = append(params, "charset="+config.Charset)
	} else {
		params = append(params, "charset=UTF8")
	}

	// 添加自定义选项
	if config.Options != "" {
		params = append(params, config.Options)
	}

	// 将参数添加到连接字符串
	if len(params) > 0 {
		dsn += "?" + strings.Join(params, "&")
	}

	// 使用GORM连接达梦数据库
	gormDB, err := gorm.Open(DaMengDialector{DSN: dsn}, &gorm.Config{
		Logger: logger.Default.LogMode(logger.Silent),
	})
	if err != nil {
		return errors.Wrap(err, "failed to open dameng connection with GORM")
	}

	// 获取底层的sql.DB对象
	sqlDB, err := gormDB.DB()
	if err != nil {
		return errors.Wrap(err, "failed to get underlying sql.DB from GORM")
	}

	// 测试连接
	if err := sqlDB.Ping(); err != nil {
		sqlDB.Close()
		return errors.Wrap(err, "failed to ping dameng database")
	}

	// 设置连接池参数
	sqlDB.SetMaxOpenConns(25)
	sqlDB.SetMaxIdleConns(5)
	sqlDB.SetConnMaxLifetime(5 * time.Minute)

	d.DB = sqlDB
	d.gormDB = gormDB
	d.Config = config
	d.Connected = true

	// 清除旧的字符集缓存
	d.clearCharsetCache()

	// 初始化字符集信息 - 提前缓存，避免后续查询时的延迟
	fmt.Println("[INFO] 正在初始化达梦数据库字符集信息...")
	isByteSemantics, charsetInfo := d.getCharsetSemantics()
	if charsetInfo != nil {
		fmt.Printf("[INFO] 成功初始化字符集信息: 字符集=%s, 字节语义=%v, 每字符字节数=%d\n",
			charsetInfo.Name, isByteSemantics, charsetInfo.BytesPerChar)
	} else {
		fmt.Println("[WARN] 初始化字符集信息失败，将使用默认值")
	}

	return nil
}

// clearCharsetCache 清除字符集缓存
func (d *DaMengDriver) clearCharsetCache() {
	d.charsetInfo = nil
	d.isByteSemantics = nil
	d.charsetCacheTime = time.Time{}
}

// GetVersion 获取达梦版本
func (d *DaMengDriver) GetVersion() (string, error) {
	if !d.IsConnected() {
		return "", ErrNotConnected
	}

	var version string
	if err := d.gormDB.Raw("SELECT BANNER FROM V$VERSION").Row().Scan(&version); err != nil {
		return "", errors.Wrap(err, "failed to get dameng version")
	}

	return version, nil
}

// ListDatabases 列出所有数据库/模式
func (d *DaMengDriver) ListDatabases(ctx context.Context) ([]models.DatabaseInfo, error) {
	if !d.IsConnected() {
		return nil, ErrNotConnected
	}

	// 存储数据库模式名称结果
	var results []struct {
		Name string `gorm:"column:name"`
	}

	// 首先尝试使用直接查询系统表，这对普通用户和管理员用户都有效
	err := d.queryAllSchemas(ctx, &results)
	if err != nil || len(results) == 0 {
		// 如果上述方法失败，回退到其他方法
		err = d.fallbackSchemaQueries(ctx, &results)
	}

	// 如果最终结果为空，则返回错误
	if len(results) == 0 {
		return nil, errors.New("failed to retrieve any schemas from database")
	}

	// 添加结果去重处理
	schemaMap := make(map[string]bool)
	var uniqueResults []struct {
		Name string `gorm:"column:name"`
	}

	for _, res := range results {
		name := strings.TrimSpace(res.Name)
		if name != "" && !schemaMap[strings.ToUpper(name)] {
			schemaMap[strings.ToUpper(name)] = true
			uniqueResults = append(uniqueResults, res)
		}
	}

	// 过滤不需要显示的系统模式
	filteredResults := d.filterSystemSchemas(uniqueResults)

	// 转换为最终结构
	databases := make([]models.DatabaseInfo, len(filteredResults))
	for i, res := range filteredResults {
		databases[i] = models.DatabaseInfo{
			Name:      res.Name,
			Charset:   "UTF8", // 达梦默认字符集
			Collation: "",     // 达梦不使用MySQL样式的排序规则
			Comment:   "",
		}
	}

	// 如果过滤后没有结果，返回原始结果
	if len(databases) == 0 && len(uniqueResults) > 0 {
		databases = make([]models.DatabaseInfo, len(uniqueResults))
		for i, res := range uniqueResults {
			databases[i] = models.DatabaseInfo{
				Name:      res.Name,
				Charset:   "UTF8",
				Collation: "",
				Comment:   "",
			}
		}
	}

	return databases, nil
}

// queryAllSchemas 查询当前用户可访问的所有模式
func (d *DaMengDriver) queryAllSchemas(ctx context.Context, results *[]struct {
	Name string `gorm:"column:name"`
}) error {
	// 博客推荐的查询方式，使用ALL_OBJECTS查询所有模式
	err1 := d.gormDB.WithContext(ctx).Raw(`
		SELECT DISTINCT 
			OBJECT_NAME as name 
		FROM ALL_OBJECTS 
		WHERE OBJECT_TYPE = 'SCH'
		ORDER BY OBJECT_NAME
	`).Scan(results).Error

	if err1 == nil && len(*results) > 0 {
		return nil
	}

	return errors.New("all schema queries failed")
}

// fallbackSchemaQueries 使用其他方法查询模式
func (d *DaMengDriver) fallbackSchemaQueries(ctx context.Context, results *[]struct {
	Name string `gorm:"column:name"`
}) error {
	// 方案1: 从数据字典视图查询
	err1 := d.gormDB.WithContext(ctx).Raw(`
		SELECT DISTINCT
			OWNER as name
		FROM ALL_OBJECTS
		ORDER BY OWNER
	`).Scan(results).Error

	if err1 == nil && len(*results) > 0 {
		return nil
	}

	// 方案2: 通过用户表查询
	err2 := d.gormDB.WithContext(ctx).Raw(`
			SELECT 
				USERNAME as name
			FROM DBA_USERS
			ORDER BY USERNAME
	`).Scan(results).Error

	if err2 == nil && len(*results) > 0 {
		return nil
	}

	// 方案3: 查询系统模式表
	err3 := d.queryDatabasesViaSysObjects(ctx, results)
	if err3 == nil && len(*results) > 0 {
		return nil
	}

	// 方案4: 使用特定的DaMeng系统表
	err4 := d.gormDB.WithContext(ctx).Raw(`
		SELECT DISTINCT
			OWNER as name
		FROM SYS.SYSOBJECTS
		WHERE OWNER IS NOT NULL
		ORDER BY OWNER
	`).Scan(results).Error

	if err4 == nil && len(*results) > 0 {
		return nil
	}

	// 方案5: 使用USER_USERS视图
	err5 := d.queryDatabasesViaUserUsers(ctx, results)
	if err5 == nil && len(*results) > 0 {
		return nil
	}

	// 最后方案: 至少返回当前用户作为一个模式
	err6 := d.queryCurrentUser(ctx, results)
	if err6 == nil && len(*results) > 0 {
		return nil
	}

	// 如果仍然失败，添加一个固定的默认用户模式列表
	*results = append(*results,
		struct {
			Name string `gorm:"column:name"`
		}{Name: "SYSDBA"},
		struct {
			Name string `gorm:"column:name"`
		}{Name: "SYSSSO"},
		struct {
			Name string `gorm:"column:name"`
		}{Name: "PUBLIC"})

	return nil
}

// 显式查询具有特定授权的模式
func (d *DaMengDriver) queryGrantedSchemas(ctx context.Context, results *[]struct {
	Name string `gorm:"column:name"`
}) error {
	// 查询当前用户有权限访问的所有模式
	queries := []string{
		// 使用系统表直接查询权限
		`SELECT DISTINCT GRANTEE as name FROM DBA_TAB_PRIVS WHERE PRIVILEGE IN ('SELECT', 'INSERT', 'UPDATE', 'DELETE')`,
		// 使用角色查询
		`SELECT DISTINCT USERNAME as name FROM USER_ROLE_PRIVS`,
		// 查询所有用户有权限的对象
		`SELECT DISTINCT OWNER as name FROM ALL_OBJECTS`,
	}

	for _, query := range queries {
		err := d.gormDB.WithContext(ctx).Raw(query).Scan(results).Error
		if err == nil && len(*results) > 0 {
			return nil
		}
	}

	return errors.New("failed to query granted schemas")
}

// queryDatabasesViaSysObjects 通过SYSOBJECTS系统表查询数据库/模式
func (d *DaMengDriver) queryDatabasesViaSysObjects(ctx context.Context, results *[]struct {
	Name string `gorm:"column:name"`
}) error {
	// 尝试两种不同的查询方式
	query1 := `
				SELECT 
					NAME as name
				FROM SYSOBJECTS 
				WHERE TYPE$ = 'SCH' 
				ORDER BY NAME
			`
	err1 := d.gormDB.WithContext(ctx).Raw(query1).Scan(results).Error

	// 如果第一种失败，尝试第二种查询
	if err1 != nil || len(*results) == 0 {
		query2 := `
			SELECT DISTINCT
				SCHEMANAME as name
			FROM SYSOBJECTS 
			WHERE SCHEMANAME IS NOT NULL
			ORDER BY SCHEMANAME
		`
		return d.gormDB.WithContext(ctx).Raw(query2).Scan(results).Error
	}

	return err1
}

// queryDatabasesViaUserUsers 通过USER_USERS视图查询数据库/模式
func (d *DaMengDriver) queryDatabasesViaUserUsers(ctx context.Context, results *[]struct {
	Name string `gorm:"column:name"`
}) error {
	query := `
		SELECT 
			USERNAME as name
		FROM USER_USERS
		ORDER BY USERNAME
	`
	return d.gormDB.WithContext(ctx).Raw(query).Scan(results).Error
}

// queryCurrentUser 获取当前用户作为唯一的模式
func (d *DaMengDriver) queryCurrentUser(ctx context.Context, results *[]struct {
	Name string `gorm:"column:name"`
}) error {
	// 尝试多种方式获取当前用户
	var currentUser string

	// 方法1: 使用DUAL
	err1 := d.gormDB.WithContext(ctx).Raw("SELECT USER FROM DUAL").Scan(&currentUser).Error
	if err1 == nil && currentUser != "" {
		*results = append(*results, struct {
			Name string `gorm:"column:name"`
		}{Name: currentUser})
		return nil
	}

	// 方法2: 使用系统会话信息
	err2 := d.gormDB.WithContext(ctx).Raw("SELECT SESSIONPROPERTY('CURRENT_USER') as USER").Scan(&currentUser).Error
	if err2 == nil && currentUser != "" {
		*results = append(*results, struct {
			Name string `gorm:"column:name"`
		}{Name: currentUser})
		return nil
	}

	// 方法3: 使用连接配置的用户名
	if d.Config != nil && d.Config.Username != "" {
		*results = append(*results, struct {
			Name string `gorm:"column:name"`
		}{Name: d.Config.Username})
		return nil
	}

	// 都失败了，返回最后一个错误
	return err2
}

// filterSystemSchemas 过滤系统模式
func (d *DaMengDriver) filterSystemSchemas(results []struct {
	Name string `gorm:"column:name"`
}) []struct {
	Name string `gorm:"column:name"`
} {
	// 定义系统模式名称映射，值为true表示需要隐藏，false表示保留
	systemSchemas := map[string]bool{
		"SYS":                true,  // 系统核心模式，隐藏
		"SYSDBA":             false, // 系统管理员模式，保留(可能包含用户对象)
		"SYSAUDITOR":         true,  // 系统审计模式，隐藏
		"PUBLIC":             false, // 公共模式，保留
		"SYSSSO":             false, // 系统安全模式，保留
		"SYSDBO":             true,  // 系统DBO模式，隐藏
		"INFORMATION_SCHEMA": true,  // 信息模式，隐藏
		"SYSTEM":             true,  // 系统模式，隐藏
	}

	var filteredResults []struct {
		Name string `gorm:"column:name"`
	}

	for _, res := range results {
		// 判断是否需要过滤：如果不在系统模式列表中，或者特别指定要保留(false)，则保留
		shouldHide, isSystem := systemSchemas[strings.ToUpper(res.Name)]
		if !isSystem || !shouldHide {
			filteredResults = append(filteredResults, res)
		}
	}

	// 如果过滤后为空，至少保留原始结果避免什么都不显示
	if len(filteredResults) == 0 {
		return results
	}

	return filteredResults
}

// ListTables 列出指定数据库/模式中的所有表
func (d *DaMengDriver) ListTables(ctx context.Context, database string) ([]models.TableInfo, error) {
	if !d.IsConnected() {
		return nil, ErrNotConnected
	}

	// 存储表信息结果
	var tableResults []tableResult
	var err error

	// 标准化数据库名称参数
	database = strings.TrimSpace(database)

	// 查询策略链实现
	// 1. 首先尝试通过ALL_TABLES视图查询
	err = d.queryTablesViaAllTables(ctx, database, &tableResults)

	// 2. 如果失败，尝试使用当前用户上下文的USER_TABLES视图
	if err != nil || len(tableResults) == 0 {
		err = d.queryTablesViaUserTables(ctx, &tableResults)
	}

	// 3. 最后尝试使用DaMeng特有的系统表
	if err != nil || len(tableResults) == 0 {
		err = d.queryTablesViaSysObjects(ctx, database, &tableResults)
	}

	// 如果所有查询都失败，返回错误
	if err != nil {
		return nil, errors.Wrap(err, "failed to list tables")
	}

	// 转换为最终结构
	tables := make([]models.TableInfo, len(tableResults))
	for i, res := range tableResults {
		tables[i] = models.TableInfo{
			Name:        res.Name,
			Type:        res.Type,
			Engine:      res.Engine,
			Collation:   "",
			RowCount:    0,
			DataLength:  0,
			IndexLength: 0,
			Comment:     res.Comment,
			CreatedAt:   "",
			Schema:      res.SchemaName, // 存储模式名
		}
	}

	return tables, nil
}

// queryTablesViaAllTables 通过ALL_TABLES视图查询表
func (d *DaMengDriver) queryTablesViaAllTables(ctx context.Context, database string, results *[]tableResult) error {
	// 使用推荐的高性能查询，带索引提示和标准的字段命名
	query := `
		SELECT /*+ INDEX(t IDX_DBA_TABLES_OWNER) */
			t.TABLE_NAME as name,
			t.OWNER as schema_name,
			'TABLE' as type,
			'DM' as engine,
			c.COMMENTS as "comment"
		FROM 
			DBA_TABLES t
		LEFT JOIN 
			DBA_TAB_COMMENTS c ON t.OWNER = c.OWNER AND t.TABLE_NAME = c.TABLE_NAME
		WHERE 
			t.OWNER = UPPER(?)
		ORDER BY 
			t.TABLE_NAME
	`

	err := d.gormDB.WithContext(ctx).Raw(query, database).Scan(results).Error

	// 如果DBA_TABLES查询失败，尝试使用ALL_TABLES
	if err != nil || len(*results) == 0 {
		query = `
			SELECT /*+ INDEX(t IDX_ALL_TABLES_OWNER) */
				t.TABLE_NAME as name,
				t.OWNER as schema_name,
				'TABLE' as type,
				'DM' as engine,
				c.COMMENTS as "comment"
			FROM 
				ALL_TABLES t
			LEFT JOIN 
				ALL_TAB_COMMENTS c ON t.OWNER = c.OWNER AND t.TABLE_NAME = c.TABLE_NAME
			WHERE 
				t.OWNER = UPPER(?)
			ORDER BY 
				t.TABLE_NAME
		`
		err = d.gormDB.WithContext(ctx).Raw(query, database).Scan(results).Error
	}

	return err
}

// queryTablesViaUserTables 通过USER_TABLES视图查询当前用户的表
func (d *DaMengDriver) queryTablesViaUserTables(ctx context.Context, results *[]tableResult) error {
	query := `
		SELECT /*+ INDEX(t IDX_USER_TABLES) */
			t.TABLE_NAME as name,
			USER as schema_name,
			'TABLE' as type,
			'DM' as engine,
			c.COMMENTS as "comment"
		FROM 
			USER_TABLES t
		LEFT JOIN 
			USER_TAB_COMMENTS c ON t.TABLE_NAME = c.TABLE_NAME
		ORDER BY 
			t.TABLE_NAME
	`
	return d.gormDB.WithContext(ctx).Raw(query).Scan(results).Error
}

// queryTablesViaSysObjects 通过SYSOBJECTS系统表查询表
func (d *DaMengDriver) queryTablesViaSysObjects(ctx context.Context, database string, results *[]tableResult) error {
	query := `
		SELECT 
			o.NAME as name,
			o.SCHEMANAME as schema_name,
			'TABLE' as type,
			'DM' as engine,
			'' as "comment"
		FROM 
			SYSOBJECTS o
		WHERE 
			o.TYPE$='SCHOBJ' AND o.SUBTYPE$='UTAB' AND o.SCHEMANAME = UPPER(?)
		ORDER BY 
			o.NAME
	`
	return d.gormDB.WithContext(ctx).Raw(query, database).Scan(results).Error
}

// queryColumnsViaMap 使用map进行查询，避免结构体字段映射问题
func (d *DaMengDriver) queryColumnsViaMap(ctx context.Context, database, table string, results *[]columnResult) error {
	var query string
	var args []interface{}

	// 根据是否为当前用户模式选择不同的查询
	if isCurrentUserSchema(d, database) {
		query = `
			SELECT 
				utc.COLUMN_NAME,
				utc.DATA_TYPE,
				utc.DATA_LENGTH,
				utc.DATA_PRECISION,
				utc.DATA_SCALE,
				CASE utc.NULLABLE WHEN 'Y' THEN 1 ELSE 0 END as NULLABLE,
				utc.COLUMN_ID,
				NVL(utc.DATA_DEFAULT, '') as DATA_DEFAULT,
				NVL(ucc.COMMENTS, '') as COMMENTS,
				CASE WHEN utc.DATA_TYPE LIKE '%CHAR%' OR utc.DATA_TYPE LIKE '%TEXT%' THEN
				  CASE WHEN utc.CHAR_USED = 'C' THEN 'CHAR' ELSE 'BYTE' END
				ELSE 'BYTE' END as CHAR_SEMANTICS
			FROM 
				USER_TAB_COLUMNS utc
			LEFT JOIN 
				USER_COL_COMMENTS ucc ON utc.TABLE_NAME = ucc.TABLE_NAME AND utc.COLUMN_NAME = ucc.COLUMN_NAME
			WHERE 
				utc.TABLE_NAME = UPPER(?)
			ORDER BY 
				utc.COLUMN_ID
		`
		args = []interface{}{table}
	} else {
		query = `
			SELECT 
				atc.COLUMN_NAME,
				atc.DATA_TYPE,
				atc.DATA_LENGTH,
				atc.DATA_PRECISION,
				atc.DATA_SCALE,
				CASE atc.NULLABLE WHEN 'Y' THEN 1 ELSE 0 END as NULLABLE,
				atc.COLUMN_ID,
				NVL(atc.DATA_DEFAULT, '') as DATA_DEFAULT,
				NVL(acc.COMMENTS, '') as COMMENTS
			FROM 
				ALL_TAB_COLUMNS atc
			LEFT JOIN 
				ALL_COL_COMMENTS acc ON atc.OWNER = acc.OWNER AND atc.TABLE_NAME = acc.TABLE_NAME AND atc.COLUMN_NAME = acc.COLUMN_NAME
			WHERE 
				atc.TABLE_NAME = UPPER(?)
				AND atc.OWNER = UPPER(?)
			ORDER BY 
				atc.COLUMN_ID
		`
		args = []interface{}{table, database}
	}

	fmt.Println("[DEBUG] 执行Map方式查询:", query)

	// 执行查询
	rows, err := d.DB.QueryContext(ctx, query, args...)
	if err != nil {
		fmt.Println("[ERROR] Map方式查询失败:", err)
		return err
	}
	defer rows.Close()

	// 获取列名
	columns, err := rows.Columns()
	if err != nil {
		fmt.Println("[ERROR] 获取列名失败:", err)
		return err
	}

	fmt.Printf("[DEBUG] 查询结果列名: %v\n", columns)

	// 遍历结果行
	for rows.Next() {
		// 创建值和指针数组
		values := make([]interface{}, len(columns))
		valuePtrs := make([]interface{}, len(columns))
		for i := range values {
			valuePtrs[i] = &values[i]
		}

		// 扫描行数据
		if err := rows.Scan(valuePtrs...); err != nil {
			fmt.Println("[ERROR] 扫描行数据失败:", err)
			continue
		}

		// 创建结果map
		rowMap := make(map[string]interface{})
		for i, col := range columns {
			var v interface{}
			val := values[i]
			b, ok := val.([]byte)
			if ok {
				v = string(b)
			} else {
				v = val
			}
			rowMap[col] = v
		}

		// 打印调试信息
		fmt.Printf("[DEBUG] 行数据: %+v\n", rowMap)

		// 构建列结果
		var colResult columnResult

		// 设置字段值（注意大小写）
		if v, ok := rowMap["COLUMN_NAME"]; ok && v != nil {
			colResult.Name = fmt.Sprintf("%v", v)
		}

		if v, ok := rowMap["DATA_TYPE"]; ok && v != nil {
			colResult.Type = fmt.Sprintf("%v", v)
		}

		if v, ok := rowMap["DATA_LENGTH"]; ok && v != nil {
			if vInt, err := strconv.ParseInt(fmt.Sprintf("%v", v), 10, 64); err == nil {
				colResult.Length = vInt
			}
		}

		if v, ok := rowMap["DATA_PRECISION"]; ok && v != nil && fmt.Sprintf("%v", v) != "<nil>" {
			if vInt, err := strconv.Atoi(fmt.Sprintf("%v", v)); err == nil {
				colResult.Precision = &vInt
			}
		}

		if v, ok := rowMap["DATA_SCALE"]; ok && v != nil && fmt.Sprintf("%v", v) != "<nil>" {
			if vInt, err := strconv.Atoi(fmt.Sprintf("%v", v)); err == nil {
				colResult.Scale = &vInt
			}
		}

		if v, ok := rowMap["NULLABLE"]; ok && v != nil {
			if vInt, err := strconv.Atoi(fmt.Sprintf("%v", v)); err == nil {
				colResult.IsNullable = vInt
			}
		}

		if v, ok := rowMap["COLUMN_ID"]; ok && v != nil {
			if vInt, err := strconv.Atoi(fmt.Sprintf("%v", v)); err == nil {
				colResult.Position = vInt
			}
		}

		// 修复默认值获取
		if v, ok := rowMap["DATA_DEFAULT"]; ok && v != nil {
			defaultValue := fmt.Sprintf("%v", v)
			// 清理默认值字符串，去除多余的引号
			defaultValue = strings.TrimSpace(defaultValue)
			if defaultValue != "" && defaultValue != "<nil>" {
				// 达梦数据库常常在默认值上添加额外的引号，需要去除
				if strings.HasPrefix(defaultValue, "'") && strings.HasSuffix(defaultValue, "'") {
					defaultValue = defaultValue[1 : len(defaultValue)-1]
				}
				colResult.DefaultValue = defaultValue
			}
		}

		// 修复注释获取
		if v, ok := rowMap["COMMENTS"]; ok && v != nil {
			comment := fmt.Sprintf("%v", v)
			comment = strings.TrimSpace(comment)
			if comment != "" && comment != "<nil>" {
				colResult.Comment = comment
			}
		}

		fmt.Printf("[DEBUG] 转换后列信息: 名称=%s, 类型=%s, 长度=%d, 默认值=%s, 注释=%s\n",
			colResult.Name, colResult.Type, colResult.Length, colResult.DefaultValue, colResult.Comment)

		// 添加到结果集
		*results = append(*results, colResult)
	}

	if err := rows.Err(); err != nil {
		fmt.Println("[ERROR] 遍历结果行出错:", err)
		return err
	}

	// 如果没有获取到列信息，尝试直接从系统表查询
	if len(*results) == 0 {
		fmt.Println("[INFO] 标准视图查询未返回结果，尝试使用系统表直接查询")
		return d.queryColumnsViaSystemTables(ctx, database, table, results)
	}

	fmt.Printf("[DEBUG] Map方式查询成功，获取到%d列\n", len(*results))
	return nil
}

// queryColumnsViaSystemTables 通过系统表直接查询列信息（用于兼容性）
func (d *DaMengDriver) queryColumnsViaSystemTables(ctx context.Context, database, table string, results *[]columnResult) error {
	query := `
		SELECT 
			a.NAME as COLUMN_NAME,
			a.TYPEID as DATA_TYPE,
			a.LENGTH as DATA_LENGTH,
			a.PRECISION as DATA_PRECISION,
			a.SCALE as DATA_SCALE,
			CASE a.NULLABLE WHEN 1 THEN 1 ELSE 0 END as NULLABLE,
			a.COLID as COLUMN_ID,
			COALESCE(a.DEFOBJNAME, '') as DATA_DEFAULT,
			COALESCE(b.COMMENT, '') as COMMENTS
		FROM 
			SYSCOLUMNS a
		LEFT JOIN 
			SYSCOMMENTS b ON a.ID = b.ID AND a.COLID = b.COLID
		JOIN 
			SYSOBJECTS o ON a.ID = o.ID
		WHERE 
			o.NAME = UPPER(?)
	`

	args := []interface{}{table}

	if !isCurrentUserSchema(d, database) {
		query += " AND o.SCHEMANAME = UPPER(?)"
		args = append(args, database)
	}

	query += " ORDER BY a.COLID"

	fmt.Println("[DEBUG] 执行系统表直接查询:", query)

	// 执行查询
	rows, err := d.DB.QueryContext(ctx, query, args...)
	if err != nil {
		fmt.Println("[ERROR] 系统表查询失败:", err)
		return err
	}
	defer rows.Close()

	// 获取列名
	columns, err := rows.Columns()
	if err != nil {
		fmt.Println("[ERROR] 获取列名失败:", err)
		return err
	}

	fmt.Printf("[DEBUG] 系统表查询结果列名: %v\n", columns)

	// 遍历结果行
	for rows.Next() {
		// 创建值和指针数组
		values := make([]interface{}, len(columns))
		valuePtrs := make([]interface{}, len(columns))
		for i := range values {
			valuePtrs[i] = &values[i]
		}

		// 扫描行数据
		if err := rows.Scan(valuePtrs...); err != nil {
			fmt.Println("[ERROR] 扫描行数据失败:", err)
			continue
		}

		// 创建结果map
		rowMap := make(map[string]interface{})
		for i, col := range columns {
			var v interface{}
			val := values[i]
			b, ok := val.([]byte)
			if ok {
				v = string(b)
			} else {
				v = val
			}
			rowMap[col] = v
		}

		// 打印调试信息
		fmt.Printf("[DEBUG] 系统表行数据: %+v\n", rowMap)

		// 构建列结果
		var colResult columnResult

		// 设置字段值（注意大小写）
		if v, ok := rowMap["COLUMN_NAME"]; ok && v != nil {
			colResult.Name = fmt.Sprintf("%v", v)
		}

		if v, ok := rowMap["DATA_TYPE"]; ok && v != nil {
			typeID := fmt.Sprintf("%v", v)
			// 根据TypeID映射到实际类型名
			colResult.Type = d.mapDaMengTypeIDToName(typeID)
		}

		if v, ok := rowMap["DATA_LENGTH"]; ok && v != nil {
			if vInt, err := strconv.ParseInt(fmt.Sprintf("%v", v), 10, 64); err == nil {
				colResult.Length = vInt
			}
		}

		if v, ok := rowMap["DATA_PRECISION"]; ok && v != nil && fmt.Sprintf("%v", v) != "<nil>" {
			if vInt, err := strconv.Atoi(fmt.Sprintf("%v", v)); err == nil {
				colResult.Precision = &vInt
			}
		}

		if v, ok := rowMap["DATA_SCALE"]; ok && v != nil && fmt.Sprintf("%v", v) != "<nil>" {
			if vInt, err := strconv.Atoi(fmt.Sprintf("%v", v)); err == nil {
				colResult.Scale = &vInt
			}
		}

		if v, ok := rowMap["NULLABLE"]; ok && v != nil {
			if vInt, err := strconv.Atoi(fmt.Sprintf("%v", v)); err == nil {
				colResult.IsNullable = vInt
			}
		}

		if v, ok := rowMap["COLUMN_ID"]; ok && v != nil {
			if vInt, err := strconv.Atoi(fmt.Sprintf("%v", v)); err == nil {
				colResult.Position = vInt
			}
		}

		// 处理默认值
		if v, ok := rowMap["DATA_DEFAULT"]; ok && v != nil {
			defaultValue := fmt.Sprintf("%v", v)
			// 清理默认值字符串，去除多余的引号
			defaultValue = strings.TrimSpace(defaultValue)
			if defaultValue != "" && defaultValue != "<nil>" {
				// 达梦数据库常常在默认值上添加额外的引号，需要去除
				if strings.HasPrefix(defaultValue, "'") && strings.HasSuffix(defaultValue, "'") {
					defaultValue = defaultValue[1 : len(defaultValue)-1]
				}
				colResult.DefaultValue = defaultValue
			}
		}

		// 处理注释
		if v, ok := rowMap["COMMENTS"]; ok && v != nil {
			comment := fmt.Sprintf("%v", v)
			comment = strings.TrimSpace(comment)
			if comment != "" && comment != "<nil>" {
				colResult.Comment = comment
			}
		}

		fmt.Printf("[DEBUG] 系统表转换后列信息: 名称=%s, 类型=%s, 长度=%d, 默认值=%s, 注释=%s\n",
			colResult.Name, colResult.Type, colResult.Length, colResult.DefaultValue, colResult.Comment)

		// 添加到结果集
		*results = append(*results, colResult)
	}

	if err := rows.Err(); err != nil {
		fmt.Println("[ERROR] 遍历结果行出错:", err)
		return err
	}

	fmt.Printf("[DEBUG] 系统表查询成功，获取到%d列\n", len(*results))
	return nil
}

// mapDaMengTypeIDToName 将达梦系统表中的TypeID映射到数据类型名称
func (d *DaMengDriver) mapDaMengTypeIDToName(typeID string) string {
	// 达梦数据库类型ID到类型名称的映射
	typeMap := map[string]string{
		"1":  "CHAR",
		"2":  "NUMBER",
		"3":  "INTEGER",
		"4":  "DATE",
		"5":  "VARCHAR",
		"6":  "VARCHAR2",
		"8":  "DOUBLE",
		"9":  "DECIMAL",
		"10": "TIMESTAMP",
		"12": "CLOB",
		"13": "BLOB",
		"16": "BINARY",
		"17": "VARBINARY",
		"18": "BOOLEAN",
		"19": "BIGINT",
		"20": "TINYINT",
		"21": "SMALLINT",
		"22": "REAL",
		"23": "TIME",
		"24": "TIMESTAMP WITH TIME ZONE",
		"25": "TIMESTAMP WITH LOCAL TIME ZONE",
		"26": "RAW",
		"27": "LONG",
		"28": "LONG RAW",
		"29": "FLOAT",
		"30": "NCHAR",
		"31": "NVARCHAR",
		"32": "NVARCHAR2",
		"33": "NCLOB",
		"34": "BIT",
		"35": "NUMERIC",
	}

	if typeName, ok := typeMap[typeID]; ok {
		return typeName
	}

	// 如果没有匹配，返回原始ID加上类型前缀，方便调试
	return "TYPE_" + typeID
}

// GetTableColumns 获取表的列信息
func (d *DaMengDriver) GetTableColumns(ctx context.Context, database, table string) ([]models.ColumnInfo, error) {
	if !d.IsConnected() {
		return nil, ErrNotConnected
	}

	// 标准化输入参数
	database = strings.TrimSpace(database)
	table = strings.TrimSpace(table)

	if table == "" {
		return nil, errors.New("table name cannot be empty")
	}

	fmt.Printf("[DEBUG] 开始获取表列信息: 数据库=%s, 表=%s\n", database, table)

	// 直接使用原生SQL查询进行调试
	directSql := `
		SELECT 
			utc.COLUMN_NAME,
			utc.DATA_TYPE
		FROM 
			USER_TAB_COLUMNS utc
		WHERE 
			utc.TABLE_NAME = UPPER(?)
		ORDER BY 
			utc.COLUMN_ID
	`
	rows, err := d.DB.QueryContext(ctx, directSql, table)
	if err != nil {
		fmt.Println("[ERROR] 直接SQL查询失败:", err)
	} else {
		fmt.Println("[DEBUG] 直接SQL查询成功，结果：")
		defer rows.Close()

		for rows.Next() {
			var colName, colType string
			if err := rows.Scan(&colName, &colType); err != nil {
				fmt.Println("[ERROR] 扫描行失败:", err)
				continue
			}
			fmt.Printf("[DEBUG] 直接SQL - 列: %s, 类型: %s\n", colName, colType)
		}
	}

	// 获取表和列注释
	comments, _ := d.collectTableComments(ctx, database, table)
	fmt.Printf("[DEBUG] 获取到注释: %v\n", comments)

	// 获取默认值
	defaults, _ := d.collectDefaultValues(ctx, database, table)
	fmt.Printf("[DEBUG] 获取到默认值: %v\n", defaults)

	// 临时结构体保存列信息结果
	var columnResults []columnResult

	// 首先尝试使用Map方式查询，这种方式最可靠
	fmt.Println("[DEBUG] 尝试使用Map方式查询列信息")
	err2 := d.queryColumnsViaMap(ctx, database, table, &columnResults)

	// 如果Map方式失败，再尝试之前的方法
	if err2 != nil || len(columnResults) == 0 {
		fmt.Println("[DEBUG] Map方式查询失败或无结果，尝试标准查询")

		// 执行查询策略链
		if isCurrentUserSchema(d, database) {
			fmt.Println("[DEBUG] 使用当前用户模式查询列信息")
			err2 = d.queryColumnsViaUserTabColumns(ctx, table, &columnResults)
		} else {
			fmt.Println("[DEBUG] 使用指定模式查询列信息:", database)
			err2 = d.queryColumnsViaAllTabColumns(ctx, database, table, &columnResults)
		}

		// 如果标准查询失败，尝试通过系统表查询
		if err2 != nil || len(columnResults) == 0 {
			fmt.Println("[DEBUG] 标准视图查询失败或无结果，尝试系统表查询")
			err2 = d.queryColumnsViaSysColumns(ctx, database, table, &columnResults)
		}
	}

	// 如果所有尝试都失败，返回错误
	if err2 != nil || len(columnResults) == 0 {
		errMsg := "failed to get table columns: no results returned"
		if err2 != nil {
			errMsg = fmt.Sprintf("failed to get table columns: %v", err2)
		}
		fmt.Println("[ERROR] 所有列查询方法都失败:", errMsg)
		return nil, errors.New(errMsg)
	}

	// 获取主键列信息
	primaryKeys := d.getPrimaryKeyColumns(ctx, database, table)
	fmt.Printf("[DEBUG] 获取到主键列: %v\n", primaryKeys)

	// 转换为最终结构
	columns := make([]models.ColumnInfo, len(columnResults))
	for i, res := range columnResults {
		// 应用注释信息，优先使用查询到的注释
		if comment, exists := comments[res.Name]; exists && comment != "" {
			res.Comment = comment
			fmt.Printf("[DEBUG] 应用注释信息: 列=%s, 注释=%s\n", res.Name, comment)
		}

		// 应用默认值信息，优先使用查询到的默认值
		if defaultVal, exists := defaults[res.Name]; exists && defaultVal != "" {
			res.DefaultValue = defaultVal
			fmt.Printf("[DEBUG] 应用默认值信息: 列=%s, 默认值=%s\n", res.Name, defaultVal)
		}

		fmt.Printf("[DEBUG] 处理列[%d]: 名称=%s, 原始类型=%s\n", i, res.Name, res.Type)
		columns[i] = d.buildColumnInfo(res, primaryKeys)
		fmt.Printf("[DEBUG] 处理后: 名称=%s, 标准类型=%s, 完整类型=%s\n",
			columns[i].Name, columns[i].Type, columns[i].FullType)
	}

	// 使用格式化工具处理列信息
	formattedColumns := FormatDaMengColumns(columns)
	fmt.Printf("[DEBUG] 格式化后列数: %d\n", len(formattedColumns))

	return formattedColumns, nil
}

// FormatDaMengColumns 格式化达梦列信息，确保与其他数据库的格式一致
func FormatDaMengColumns(columns []models.ColumnInfo) []models.ColumnInfo {
	fmt.Println("[DEBUG] 开始格式化达梦列信息...")

	for i := range columns {
		// 确保字段有有效值
		if columns[i].Comment == "" {
			columns[i].Comment = ""
		}

		// 确保数值类型长度和精度正确
		if strings.Contains(strings.ToUpper(columns[i].Type), "NUMBER") ||
			strings.Contains(strings.ToUpper(columns[i].Type), "DECIMAL") {
			// 如果精度和刻度都有值，确保长度字段显示为 "精度,刻度" 格式
			if columns[i].Precision > 0 && columns[i].Scale > 0 {
				columns[i].LengthDisplay = fmt.Sprintf("%d,%d", columns[i].Precision, columns[i].Scale)
			} else if columns[i].Precision > 0 {
				columns[i].LengthDisplay = fmt.Sprintf("%d", columns[i].Precision)
			}
		}

		// 确保字符类型长度正确
		if strings.Contains(strings.ToUpper(columns[i].Type), "CHAR") ||
			strings.Contains(strings.ToUpper(columns[i].Type), "VARCHAR") {
			if columns[i].Length > 0 {
				columns[i].LengthDisplay = fmt.Sprintf("%d", columns[i].Length)
			}

			// 添加字符集信息
			if columns[i].Charset == "" {
				columns[i].Charset = "UTF8" // 默认UTF8
			}
		}

		// 确保RawInfo中也包含这些信息
		if columns[i].RawInfo == nil {
			columns[i].RawInfo = make(map[string]interface{})
		}

		// 更新RawInfo
		columns[i].RawInfo["lengthDisplay"] = columns[i].LengthDisplay
		columns[i].RawInfo["comment"] = columns[i].Comment

		fmt.Printf("[DEBUG] 格式化列 %s: 类型=%s, 长度显示=%s, 注释=%s\n",
			columns[i].Name, columns[i].Type, columns[i].LengthDisplay, columns[i].Comment)
	}

	return columns
}

// queryColumnsViaUserTabColumns 通过USER_TAB_COLUMNS视图查询列
func (d *DaMengDriver) queryColumnsViaUserTabColumns(ctx context.Context, table string, results *[]columnResult) error {
	// 根据达梦数据库官方数据字典视图查询
	query := `
			SELECT 
			utc.COLUMN_NAME as name,
			utc.DATA_TYPE as data_type,
			utc.DATA_LENGTH as length,
			utc.DATA_PRECISION as precision,
			utc.DATA_SCALE as scale,
			CASE utc.NULLABLE WHEN 'Y' THEN 1 ELSE 0 END as is_nullable,
			utc.COLUMN_ID as position,
			utc.DATA_DEFAULT as default_value,
			NVL(ucc.COMMENTS, '') as "comment"
		FROM 
			USER_TAB_COLUMNS utc
		LEFT JOIN 
			USER_COL_COMMENTS ucc ON utc.TABLE_NAME = ucc.TABLE_NAME AND utc.COLUMN_NAME = ucc.COLUMN_NAME
		WHERE 
			utc.TABLE_NAME = UPPER(?)
		ORDER BY 
			utc.COLUMN_ID
	`

	fmt.Println("[DEBUG] 执行USER_TAB_COLUMNS查询:", query, "表名:", table)

	err := d.gormDB.WithContext(ctx).Raw(query, table).Scan(results).Error

	if err != nil {
		fmt.Println("[ERROR] USER_TAB_COLUMNS查询失败:", err)
	} else {
		fmt.Printf("[DEBUG] USER_TAB_COLUMNS查询结果: 获取到%d列\n", len(*results))
		for i, col := range *results {
			fmt.Printf("[DEBUG] 列[%d]: 名称=%s, 类型=%s, 长度=%d\n",
				i, col.Name, col.Type, col.Length)
		}
	}

	return err
}

// queryColumnsViaAllTabColumns 通过ALL_TAB_COLUMNS视图查询列
func (d *DaMengDriver) queryColumnsViaAllTabColumns(ctx context.Context, database, table string, results *[]columnResult) error {
	// 使用达梦数据库官方数据字典视图查询
	query := `
				SELECT 
			atc.COLUMN_NAME as name,
			atc.DATA_TYPE as data_type,
			atc.DATA_LENGTH as length,
			atc.DATA_PRECISION as precision,
			atc.DATA_SCALE as scale,
			CASE atc.NULLABLE WHEN 'Y' THEN 1 ELSE 0 END as is_nullable,
			atc.COLUMN_ID as position,
			atc.DATA_DEFAULT as default_value,
			NVL(acc.COMMENTS, '') as "comment"
		FROM 
			ALL_TAB_COLUMNS atc
		LEFT JOIN 
			ALL_COL_COMMENTS acc ON atc.OWNER = acc.OWNER AND atc.TABLE_NAME = acc.TABLE_NAME AND atc.COLUMN_NAME = acc.COLUMN_NAME
		WHERE 
			atc.TABLE_NAME = UPPER(?)
			AND atc.OWNER = UPPER(?)
		ORDER BY 
			atc.COLUMN_ID
	`

	fmt.Println("[DEBUG] 执行ALL_TAB_COLUMNS查询:", query, "表名:", table, "模式:", database)

	err := d.gormDB.WithContext(ctx).Raw(query, table, database).Scan(results).Error

	if err != nil {
		fmt.Println("[ERROR] ALL_TAB_COLUMNS查询失败:", err)
	} else {
		fmt.Printf("[DEBUG] ALL_TAB_COLUMNS查询结果: 获取到%d列\n", len(*results))
		for i, col := range *results {
			fmt.Printf("[DEBUG] 列[%d]: 名称=%s, 类型=%s, 长度=%d\n",
				i, col.Name, col.Type, col.Length)
		}
	}

	return err
}

// queryColumnsViaSysColumns 通过系统表查询列
func (d *DaMengDriver) queryColumnsViaSysColumns(ctx context.Context, database, table string, results *[]columnResult) error {
	// 尝试直接使用USER_TAB_COLUMNS查询
	// 在大多数情况下，这应该是最可靠的方法
	query := `
		SELECT 
			COLUMN_NAME as name,
			DATA_TYPE as data_type,
			DATA_LENGTH as length,
			DATA_PRECISION as precision,
			DATA_SCALE as scale,
			CASE NULLABLE WHEN 'Y' THEN 1 ELSE 0 END as is_nullable,
			COLUMN_ID as position,
			DATA_DEFAULT as default_value,
			'' as "comment"
		FROM 
			USER_TAB_COLUMNS
		WHERE 
			TABLE_NAME = UPPER(?)
		ORDER BY 
			COLUMN_ID
	`

	fmt.Println("[DEBUG] 执行USER_TAB_COLUMNS备用查询:", query, "表名:", table)

	userErr := d.gormDB.WithContext(ctx).Raw(query, table).Scan(results).Error

	if userErr != nil {
		fmt.Println("[ERROR] USER_TAB_COLUMNS备用查询失败:", userErr)
	} else {
		fmt.Printf("[DEBUG] USER_TAB_COLUMNS备用查询结果: 获取到%d列\n", len(*results))
		for i, col := range *results {
			fmt.Printf("[DEBUG] 列[%d]: 名称=%s, 类型=%s, 长度=%d\n",
				i, col.Name, col.Type, col.Length)
		}
	}

	if userErr == nil && len(*results) > 0 {
		return nil
	}

	// 如果USER_TAB_COLUMNS查询失败，尝试ALL_TAB_COLUMNS
	query = `
		SELECT 
			COLUMN_NAME as name,
			DATA_TYPE as data_type,
			DATA_LENGTH as length,
			DATA_PRECISION as precision,
			DATA_SCALE as scale,
			CASE NULLABLE WHEN 'Y' THEN 1 ELSE 0 END as is_nullable,
			COLUMN_ID as position,
			DATA_DEFAULT as default_value,
			'' as "comment"
		FROM 
			ALL_TAB_COLUMNS
		WHERE 
			TABLE_NAME = UPPER(?)
			AND OWNER = UPPER(?)
		ORDER BY 
			COLUMN_ID
	`

	fmt.Println("[DEBUG] 执行ALL_TAB_COLUMNS备用查询:", query, "表名:", table, "模式:", database)

	allErr := d.gormDB.WithContext(ctx).Raw(query, table, database).Scan(results).Error

	if allErr != nil {
		fmt.Println("[ERROR] ALL_TAB_COLUMNS备用查询失败:", allErr)
	} else {
		fmt.Printf("[DEBUG] ALL_TAB_COLUMNS备用查询结果: 获取到%d列\n", len(*results))
		for i, col := range *results {
			fmt.Printf("[DEBUG] 列[%d]: 名称=%s, 类型=%s, 长度=%d\n",
				i, col.Name, col.Type, col.Length)
		}
	}

	if allErr == nil && len(*results) > 0 {
		return nil
	}

	// 最后尝试使用简化查询
	// 注意：这里不再使用系统表
	if userErr != nil && allErr != nil {
		return errors.Wrap(userErr, "failed to get table columns after multiple attempts")
	}

	return nil
}

// getPrimaryKeyColumns 获取表的主键列
func (d *DaMengDriver) getPrimaryKeyColumns(ctx context.Context, database, table string) map[string]bool {
	primaryKeys := make(map[string]bool)

	// 通过约束信息获取主键列
	type pkResult struct {
		Name string `gorm:"column:name"`
	}

	var pkResults []pkResult
	var query string
	var args []interface{}

	// 根据是否当前用户模式选择查询方式
	if isCurrentUserSchema(d, database) {
		query = `
			SELECT /*+ USE_HASH(c cc) LEADING(c) */
				cc.COLUMN_NAME as name
			FROM 
				USER_CONSTRAINTS c
			JOIN 
				USER_CONS_COLUMNS cc ON c.CONSTRAINT_NAME = cc.CONSTRAINT_NAME
			WHERE 
				c.CONSTRAINT_TYPE = 'P'
				AND c.TABLE_NAME = UPPER(?)
			ORDER BY 
				cc.POSITION
		`
		args = []interface{}{table}
	} else {
		query = `
			SELECT /*+ USE_HASH(c cc) LEADING(c) */
				cc.COLUMN_NAME as name
			FROM 
				ALL_CONSTRAINTS c
			JOIN 
				ALL_CONS_COLUMNS cc ON c.CONSTRAINT_NAME = cc.CONSTRAINT_NAME AND c.OWNER = cc.OWNER
			WHERE 
				c.CONSTRAINT_TYPE = 'P'
				AND c.TABLE_NAME = UPPER(?)
				AND c.OWNER = UPPER(?)
			ORDER BY 
				cc.POSITION
		`
		args = []interface{}{table, database}
	}

	// 执行查询并忽略错误 - 对于无主键的表，仍需继续处理
	d.gormDB.WithContext(ctx).Raw(query, args...).Scan(&pkResults)

	// 如果第一种方法没有找到主键，尝试另一种方法
	if len(pkResults) == 0 {
		// 尝试通过索引和约束信息查询主键
		fallbackQuery := `
			SELECT /*+ USE_HASH(i ic c) LEADING(i) */
				ic.COLUMN_NAME as name
			FROM 
				USER_INDEXES i
			JOIN 
				USER_IND_COLUMNS ic ON i.INDEX_NAME = ic.INDEX_NAME
			JOIN 
				USER_CONSTRAINTS c ON i.INDEX_NAME = c.CONSTRAINT_NAME
			WHERE 
				c.CONSTRAINT_TYPE = 'P'
				AND i.TABLE_NAME = UPPER(?) 
			ORDER BY 
				ic.COLUMN_POSITION
		`
		d.gormDB.WithContext(ctx).Raw(fallbackQuery, table).Scan(&pkResults)
	}

	// 如果前两种方法都未找到主键，尝试使用系统表查询
	if len(pkResults) == 0 {
		// 使用兼容不同版本达梦的系统表查询主键列
		sysQuery := `
			SELECT /*+ USE_HASH(i o c) */
				c.NAME as name
			FROM 
				SYSINDEXES i
			JOIN 
				SYSOBJECTS o ON i.ID = o.ID
			JOIN 
				SYSCOLUMNS c ON c.ID = o.ID AND c.COLID = i.KEYNO
			WHERE 
				i.ISPRIMARY = 1
				AND o.NAME = UPPER(?)
			ORDER BY 
				c.COLID
		`
		d.gormDB.WithContext(ctx).Raw(sysQuery, table).Scan(&pkResults)

		// 如果上面的查询失败，尝试使用另一种方式
		if len(pkResults) == 0 {
			// 尝试使用ALL_CONS_COLUMNS视图查询
			allConsQuery := `
				SELECT /*+ USE_HASH(c cc) */
					cc.COLUMN_NAME as name
				FROM 
					ALL_CONSTRAINTS c
				JOIN 
					ALL_CONS_COLUMNS cc ON c.CONSTRAINT_NAME = cc.CONSTRAINT_NAME
				WHERE 
					c.CONSTRAINT_TYPE = 'P'
					AND c.TABLE_NAME = UPPER(?)
				ORDER BY 
					cc.POSITION
			`
			d.gormDB.WithContext(ctx).Raw(allConsQuery, table).Scan(&pkResults)
		}
	}

	// 将主键列名添加到映射中
	for _, pk := range pkResults {
		primaryKeys[pk.Name] = true
	}

	return primaryKeys
}

// buildColumnInfo 构建列信息
func (d *DaMengDriver) buildColumnInfo(res columnResult, primaryKeys map[string]bool) models.ColumnInfo {
	fmt.Printf("[DEBUG] 开始构建列信息: 名称=%s, 原始类型=%s\n", res.Name, res.Type)

	// 映射数据类型
	standardType := d.mapDaMengTypeToStandard(res.Type)
	fmt.Printf("[DEBUG] 开始映射数据类型: %s\n", res.Type)
	fmt.Printf("[DEBUG] 类型映射: %s -> %s\n", res.Type, standardType)

	// 获取字符集信息
	isByteSemantics, charsetInfo := d.getCharsetSemantics()
	bytesPerChar := 1
	if charsetInfo != nil {
		bytesPerChar = charsetInfo.BytesPerChar
	}

	fmt.Printf("[DEBUG] 使用缓存的字符集信息: 字符集=%s, 字节语义=%v, 每字符字节数=%d\n",
		charsetInfo.Name, isByteSemantics, bytesPerChar)

	// 调整长度显示
	length := res.Length
	var lengthDisplay string

	// 根据类型调整长度
	if isCharType(standardType) {
		// 获取字符语义
		semanticType := res.CharSemantics
		if semanticType == "" {
			semanticType = "BYTE" // 默认字节语义
		}

		// 字符列长度语义检查
		fmt.Printf("[DEBUG] 字符列语义检查: 类型=%s, 原始长度=%d, 字节语义=%v, 字符集=%v\n",
			standardType, length, semanticType == "BYTE", charsetInfo)

		// 如果是字节语义，且有字符集信息，需要转换为字符数
		if semanticType == "BYTE" && bytesPerChar > 0 {
			// 调整为字符长度
			fmt.Printf("[DEBUG] 字节语义调整: 原始长度=%d字节 / %d字节每字符 = %d字符\n",
				length, bytesPerChar, length/int64(bytesPerChar))
			length = length / int64(bytesPerChar)
		}

		fmt.Printf("[DEBUG] 调整后的长度: %d\n", length)
		fmt.Printf("[DEBUG] 字符类型长度显示: %d\n", length)
		lengthDisplay = fmt.Sprintf("%d", length)

		// 保存语义类型
		fmt.Printf("[DEBUG] 语义类型: %s\n", semanticType)
	} else if isPrecisionType(standardType) && res.Precision != nil && res.Scale != nil {
		// 精度类型(NUMERIC, DECIMAL)，显示为precision,scale
		fmt.Printf("[DEBUG] 调整后的长度: %d\n", length)
		fmt.Printf("[DEBUG] 数值类型(精度,刻度)显示: %d,%d\n", *res.Precision, *res.Scale)
		lengthDisplay = fmt.Sprintf("%d,%d", *res.Precision, *res.Scale)
	} else {
		// 其他类型直接显示长度
		fmt.Printf("[DEBUG] 调整后的长度: %d\n", length)
		fmt.Printf("[DEBUG] 其他类型长度显示: %d\n", length)
		lengthDisplay = fmt.Sprintf("%d", length)
	}

	// 保存语义类型
	semanticType := "BYTE"
	if res.CharSemantics != "" {
		semanticType = res.CharSemantics
	}
	fmt.Printf("[DEBUG] 语义类型: %s\n", semanticType)

	// 构建完整类型名
	fullType := buildFullTypeName(standardType, length, res.Precision, res.Scale, semanticType)
	fmt.Printf("[DEBUG] 构建完整类型名: 类型=%s, 长度=%d, 精度=%v, 刻度=%v\n",
		standardType, length, res.Precision, res.Scale)
	fmt.Printf("[DEBUG] 完整类型: %s\n", fullType)

	// 设置列属性
	isPrimary := primaryKeys[res.Name]
	fmt.Printf("[DEBUG] 列属性: 主键=%v, 自增=%v\n", isPrimary, false) // 目前无法检测自增

	// 设置列注释
	fmt.Printf("[DEBUG] 列注释: %s\n", res.Comment)

	// 从指针转换为int值
	precision := 0
	if res.Precision != nil {
		precision = *res.Precision
	}

	scale := 0
	if res.Scale != nil {
		scale = *res.Scale
	}

	// 构建最终列信息
	columnInfo := models.ColumnInfo{
		Name:            res.Name,
		Type:            standardType,
		FullType:        fullType,
		Length:          int(length),
		LengthDisplay:   lengthDisplay,
		SemanticType:    semanticType,
		OriginalLength:  res.Length,
		BytesPerChar:    bytesPerChar,
		Precision:       precision,
		Scale:           scale,
		IsNullable:      res.IsNullable == 1,
		NotNull:         res.IsNullable != 1,
		IsPrimaryKey:    isPrimary,
		PrimaryKey:      isPrimary,
		IsAutoIncrement: false,
		AutoIncrement:   false,
		Position:        res.Position,
		DefaultValue:    res.DefaultValue,
		Comment:         res.Comment,
		Charset:         charsetInfo.Name,
		Collation:       "",
		Extra:           "",
		RawInfo: map[string]interface{}{
			"name":            res.Name,
			"type":            standardType,
			"originalType":    res.Type,
			"originalLength":  res.Length,
			"lengthDisplay":   lengthDisplay,
			"semanticType":    semanticType,
			"bytesPerChar":    bytesPerChar,
			"isNullable":      res.IsNullable == 1,
			"isPrimaryKey":    isPrimary,
			"isAutoIncrement": false,
			"fullType":        fullType,
			"defaultValue":    res.DefaultValue,
			"comment":         res.Comment,
		},
	}

	fmt.Printf("[DEBUG] 完整列信息: %+v\n", columnInfo)

	return columnInfo
}

// buildFullTypeName 构建完整类型名称，包含长度、精度、刻度信息
func buildFullTypeName(typeName string, length int64, precision, scale *int, semanticType string) string {
	if isPrecisionType(typeName) && precision != nil && scale != nil {
		return fmt.Sprintf("%s(%d,%d)", typeName, *precision, *scale)
	} else if isCharType(typeName) && length > 0 {
		// 对于字符类型，包含语义信息
		return fmt.Sprintf("%s(%d %s)", typeName, length, semanticType)
	} else if needsLength(typeName) && length > 0 {
		return fmt.Sprintf("%s(%d)", typeName, length)
	} else if typeName == "TIMESTAMP" && scale != nil {
		return fmt.Sprintf("%s(%d)", typeName, *scale)
	}
	return typeName
}

// getAdjustedLength 根据数据类型获取调整后的长度值
func (d *DaMengDriver) getAdjustedLength(res columnResult) int64 {
	// 如果没有长度，返回0
	if res.Length <= 0 {
		return 0
	}

	// 统一转为大写进行比较
	upperType := strings.ToUpper(res.Type)

	// 对于CHAR, VARCHAR, VARCHAR2等字符类型的处理
	if strings.Contains(upperType, "CHAR") {
		// 记录原始长度，方便调试
		originalLength := res.Length

		// 检查达梦的语义设置(字节语义或字符语义)
		isByteSemantics, charsetInfo := d.getCharsetSemantics()

		fmt.Printf("[DEBUG] 字符列语义检查: 类型=%s, 原始长度=%d, 字节语义=%v, 字符集=%v\n",
			upperType, originalLength, isByteSemantics, charsetInfo)

		// 获取每个字符占用的字节数
		bytesPerChar := 1
		if charsetInfo != nil {
			bytesPerChar = charsetInfo.BytesPerChar
		}

		// 如果是N开头的Unicode类型(NCHAR, NVARCHAR等)
		if strings.HasPrefix(upperType, "N") {
			// 这些类型固定使用Unicode编码，通常是UTF-16，每个字符2字节
			if isByteSemantics {
				// 记录转换过程
				adjustedLength := originalLength / 2
				fmt.Printf("[DEBUG] NCHAR类型调整: %d字节 / 2 = %d字符\n",
					originalLength, adjustedLength)
				return adjustedLength
			}
			return originalLength
		}

		// 对于普通的VARCHAR类型
		if isByteSemantics && bytesPerChar > 1 {
			// 如果是字节语义且每个字符占多个字节，需要除以字节数得到字符数
			adjustedLength := originalLength / int64(bytesPerChar)
			fmt.Printf("[DEBUG] 字节语义调整: 原始长度=%d字节 / %d字节每字符 = %d字符\n",
				originalLength, bytesPerChar, adjustedLength)
			return adjustedLength
		}

		// 如果是字符语义或每字符1字节的编码，直接返回原始长度
		return originalLength
	}

	// 对于CLOB, BLOB等LOB类型，通常返回最大长度
	if strings.Contains(upperType, "LOB") || strings.Contains(upperType, "TEXT") {
		return res.Length
	}

	// 对于NUMBER, DECIMAL类型，长度由精度和刻度决定
	if strings.Contains(upperType, "NUMBER") || strings.Contains(upperType, "DECIMAL") {
		// 对于精度已定义的数值类型，返回精度作为长度
		if res.Precision != nil && *res.Precision > 0 {
			return int64(*res.Precision)
		}
		// 如果没有精度，返回原始长度
		return res.Length
	}

	// 对于其他类型，返回原始长度
	return res.Length
}

// mapDaMengTypeToStandard 映射达梦数据类型到标准类型
func (d *DaMengDriver) mapDaMengTypeToStandard(dataType string) string {
	fmt.Printf("[DEBUG] 开始映射数据类型: %s\n", dataType)

	// 检查空类型
	if dataType == "" {
		fmt.Println("[WARN] 空数据类型，返回VARCHAR2作为默认类型")
		return "VARCHAR2"
	}

	// 确保类型名称统一为大写处理
	originalType := strings.ToUpper(strings.TrimSpace(dataType))

	// 处理可能包含模式前缀的类型，例如 "SYS.VARCHAR" -> "VARCHAR"
	if strings.Contains(originalType, ".") {
		parts := strings.Split(originalType, ".")
		originalType = parts[len(parts)-1]
		fmt.Printf("[DEBUG] 移除模式前缀后: %s\n", originalType)
	}

	// 达梦数据库类型映射
	typeMap := map[string]string{
		"CHAR":          "CHAR",
		"VARCHAR":       "VARCHAR",
		"VARCHAR2":      "VARCHAR2",
		"NCHAR":         "NCHAR",
		"NVARCHAR":      "NVARCHAR",
		"NVARCHAR2":     "NVARCHAR2",
		"CLOB":          "CLOB",
		"BLOB":          "BLOB",
		"INT":           "INT",
		"INTEGER":       "INTEGER",
		"BIGINT":        "BIGINT",
		"SMALLINT":      "SMALLINT",
		"TINYINT":       "TINYINT",
		"NUMBER":        "NUMBER",
		"DECIMAL":       "DECIMAL",
		"NUMERIC":       "NUMERIC",
		"FLOAT":         "FLOAT",
		"DOUBLE":        "DOUBLE",
		"REAL":          "REAL",
		"BINARY_FLOAT":  "BINARY_FLOAT",
		"BINARY_DOUBLE": "BINARY_DOUBLE",
		"DATE":          "DATE",
		"TIME":          "TIME",
		"TIMESTAMP":     "TIMESTAMP",
		"TIMESTAMP(6)":  "TIMESTAMP",
		"BOOLEAN":       "BOOLEAN",
		"BIT":           "BIT",
		"BINARY":        "BINARY",
		"VARBINARY":     "VARBINARY",
		"INTERVAL YEAR": "INTERVAL YEAR",
		"INTERVAL DAY":  "INTERVAL DAY",
		"RAW":           "RAW",
		"LONG":          "LONG",
		"LONG RAW":      "LONG RAW",
		"ROWID":         "ROWID",
	}

	// 尝试直接映射
	if mappedType, exists := typeMap[originalType]; exists {
		fmt.Printf("[DEBUG] 直接映射: %s -> %s\n", originalType, mappedType)
		return mappedType
	}

	// 尝试模糊匹配 (例如TIMESTAMP(9)这样带精度的类型)
	for baseType, mappedType := range typeMap {
		if strings.HasPrefix(originalType, baseType) {
			fmt.Printf("[DEBUG] 前缀匹配: %s -> %s\n", originalType, mappedType)
			return mappedType
		}
	}

	// 如果无法映射，返回原始类型
	fmt.Printf("[DEBUG] 无法映射，使用原始类型: %s\n", originalType)
	return originalType
}

// isCharType 判断是否为字符类型
func isCharType(dataType string) bool {
	return strings.Contains(strings.ToUpper(dataType), "CHAR") ||
		strings.Contains(strings.ToUpper(dataType), "VARCHAR") ||
		strings.Contains(strings.ToUpper(dataType), "VARCHAR2") ||
		strings.Contains(strings.ToUpper(dataType), "NCHAR") ||
		strings.Contains(strings.ToUpper(dataType), "NVARCHAR") ||
		strings.Contains(strings.ToUpper(dataType), "NVARCHAR2")
}

// isPrecisionType 判断是否为精度类型
func isPrecisionType(dataType string) bool {
	return strings.Contains(strings.ToUpper(dataType), "NUMBER") ||
		strings.Contains(strings.ToUpper(dataType), "DECIMAL") ||
		strings.Contains(strings.ToUpper(dataType), "NUMERIC")
}

// needsLength 判断是否需要长度
func needsLength(dataType string) bool {
	return strings.Contains(strings.ToUpper(dataType), "CHAR") ||
		strings.Contains(strings.ToUpper(dataType), "VARCHAR") ||
		strings.Contains(strings.ToUpper(dataType), "VARCHAR2") ||
		strings.Contains(strings.ToUpper(dataType), "BINARY") ||
		strings.Contains(strings.ToUpper(dataType), "VARBINARY") ||
		strings.Contains(strings.ToUpper(dataType), "RAW")
}

// isAutoIncrementColumn 判断是否为自增列
func (d *DaMengDriver) isAutoIncrementColumn(res columnResult, isPrimaryKey bool) bool {
	// 1. 检查默认值是否包含自增序列引用
	defaultUpper := strings.ToUpper(res.DefaultValue)
	if strings.Contains(defaultUpper, "IDENTITY") ||
		strings.Contains(defaultUpper, "SEQ") ||
		strings.Contains(defaultUpper, "NEXTVAL") {
		return true
	}

	// 2. 检查类型是否为IDENTITY
	if strings.Contains(strings.ToUpper(res.Type), "IDENTITY") {
		return true
	}

	// 3. 基于类型和主键状态判断
	typeUpper := strings.ToUpper(res.Type)
	if isPrimaryKey && (typeUpper == "INTEGER" ||
		typeUpper == "BIGINT" ||
		typeUpper == "INT" ||
		typeUpper == "NUMBER" && (res.Scale == nil || *res.Scale == 0)) {

		// 如果是主键且是整数类型，可能是自增列
		// 注意：这是一个启发式判断，可能不准确，需要结合默认值等其他信息

		// 对于NUMBER类型，只有在没有小数部分时才可能是自增列
		if typeUpper == "NUMBER" && (res.Precision != nil && *res.Precision > 0) {
			return true
		}

		// 对于其他整数类型，如果是主键则更可能是自增列
		if typeUpper == "INTEGER" || typeUpper == "BIGINT" || typeUpper == "INT" {
			return true
		}
	}

	return false
}

// GetTableIndexes 获取表的索引信息
func (d *DaMengDriver) GetTableIndexes(ctx context.Context, database, table string) ([]models.IndexInfo, error) {
	if !d.IsConnected() {
		return nil, ErrNotConnected
	}

	// 标准化输入参数
	database = strings.TrimSpace(database)
	table = strings.TrimSpace(table)

	if table == "" {
		return nil, errors.New("table name cannot be empty")
	}

	// 查询索引
	var indexResults []indexResult
	var err error

	// 查询策略链实现
	// 1. 通过标准视图查询索引
	if isCurrentUserSchema(d, database) {
		err = d.queryIndexesViaUserIndexes(ctx, table, &indexResults)
	} else {
		err = d.queryIndexesViaAllIndexes(ctx, database, table, &indexResults)
	}

	// 2. 如果标准查询失败，尝试通过系统表查询
	if err != nil || len(indexResults) == 0 {
		err = d.queryIndexesViaSysIndexes(ctx, database, table, &indexResults)
	}

	// 没有索引时返回空列表
	if len(indexResults) == 0 {
		return []models.IndexInfo{}, nil
	}

	// 查询索引列
	indexColumnsMap := d.getIndexColumns(ctx, database, table)

	// 查询主键约束名称
	primaryKeyNames := d.getPrimaryKeyNames(ctx, database, table)

	// 构造最终索引结果
	indexes := make([]models.IndexInfo, len(indexResults))
	for i, idx := range indexResults {
		// 确定索引类型
		indexType := idx.Type
		if indexType == "" {
			indexType = "BTREE" // 达梦默认使用B树索引
		}

		indexes[i] = models.IndexInfo{
			Name:      idx.Name,
			Type:      indexType,
			IsUnique:  idx.Uniqueness == "UNIQUE",
			IsPrimary: primaryKeyNames[idx.Name],
			Columns:   indexColumnsMap[idx.Name],
			Comment:   "",
		}
	}

	return indexes, nil
}

// queryIndexesViaUserIndexes 通过USER_INDEXES视图查询索引
func (d *DaMengDriver) queryIndexesViaUserIndexes(ctx context.Context, table string, results *[]indexResult) error {
	query := `
		SELECT /*+ INDEX(i IDX_USER_INDEXES) */
			i.INDEX_NAME as name,
			i.UNIQUENESS as uniqueness,
			i.INDEX_TYPE as index_type,
			i.STATUS as status
		FROM 
			USER_INDEXES i
		WHERE 
			i.TABLE_NAME = UPPER(?)
			AND i.INDEX_TYPE != 'LOB'
		ORDER BY 
			i.INDEX_NAME
	`
	return d.gormDB.WithContext(ctx).Raw(query, table).Scan(results).Error
}

// queryIndexesViaAllIndexes 通过ALL_INDEXES视图查询索引
func (d *DaMengDriver) queryIndexesViaAllIndexes(ctx context.Context, database, table string, results *[]indexResult) error {
	query := `
		SELECT /*+ INDEX(i IDX_ALL_INDEXES) */
			i.INDEX_NAME as name,
			i.UNIQUENESS as uniqueness,
			i.INDEX_TYPE as index_type,
			i.STATUS as status
		FROM 
			ALL_INDEXES i
		WHERE 
			i.TABLE_NAME = UPPER(?)
			AND i.OWNER = UPPER(?)
			AND i.INDEX_TYPE != 'LOB'
		ORDER BY 
			i.INDEX_NAME
	`
	return d.gormDB.WithContext(ctx).Raw(query, table, database).Scan(results).Error
}

// queryIndexesViaSysIndexes 通过SYSINDEXES系统表查询索引
func (d *DaMengDriver) queryIndexesViaSysIndexes(ctx context.Context, database, table string, results *[]indexResult) error {
	query := `
			SELECT 
			i.NAME as name,
			CASE i.ISUNIQUE WHEN 1 THEN 'UNIQUE' ELSE 'NONUNIQUE' END as uniqueness,
			'BTREE' as index_type,
			'VALID' as status
		FROM 
			SYSINDEXES i
		JOIN 
			SYSOBJECTS o ON i.ID = o.ID
		WHERE 
			o.NAME = UPPER(?)
	`

	args := []interface{}{table}

	if !isCurrentUserSchema(d, database) {
		query += " AND o.SCHEMANAME = UPPER(?)"
		args = append(args, database)
	} else {
		query += " AND o.SCHEMANAME = USER"
	}

	query += " ORDER BY i.NAME"

	return d.gormDB.WithContext(ctx).Raw(query, args...).Scan(results).Error
}

// getIndexColumns 获取索引列信息
func (d *DaMengDriver) getIndexColumns(ctx context.Context, database, table string) map[string][]string {
	indexColumnsMap := make(map[string][]string)

	var indexColumnResults []indexColumnResult
	var err error

	// 1. 通过标准视图查询索引列
	if isCurrentUserSchema(d, database) {
		err = d.queryIndexColumnsViaUserIndColumns(ctx, table, &indexColumnResults)
	} else {
		err = d.queryIndexColumnsViaAllIndColumns(ctx, database, table, &indexColumnResults)
	}

	// 2. 如果标准查询失败，尝试通过系统表查询
	if err != nil || len(indexColumnResults) == 0 {
		err = d.queryIndexColumnsViaSysIndexCols(ctx, database, table, &indexColumnResults)
	}

	// 整理索引列
	for _, col := range indexColumnResults {
		indexColumnsMap[col.IndexName] = append(indexColumnsMap[col.IndexName], col.ColumnName)
	}

	return indexColumnsMap
}

// queryIndexColumnsViaUserIndColumns 通过USER_IND_COLUMNS视图查询索引列
func (d *DaMengDriver) queryIndexColumnsViaUserIndColumns(ctx context.Context, table string, results *[]indexColumnResult) error {
	query := `
		SELECT /*+ INDEX(ic IDX_USER_IND_COLUMNS) */
			ic.INDEX_NAME as index_name,
			ic.COLUMN_NAME as column_name,
			ic.COLUMN_POSITION as column_position
		FROM 
			USER_IND_COLUMNS ic
		WHERE 
			ic.TABLE_NAME = UPPER(?)
		ORDER BY 
			ic.INDEX_NAME, ic.COLUMN_POSITION
	`
	return d.gormDB.WithContext(ctx).Raw(query, table).Scan(results).Error
}

// queryIndexColumnsViaAllIndColumns 通过ALL_IND_COLUMNS视图查询索引列
func (d *DaMengDriver) queryIndexColumnsViaAllIndColumns(ctx context.Context, database, table string, results *[]indexColumnResult) error {
	query := `
		SELECT /*+ INDEX(ic IDX_ALL_IND_COLUMNS) */
			ic.INDEX_NAME as index_name,
			ic.COLUMN_NAME as column_name,
			ic.COLUMN_POSITION as column_position
		FROM 
			ALL_IND_COLUMNS ic
		WHERE 
			ic.TABLE_NAME = UPPER(?)
			AND ic.TABLE_OWNER = UPPER(?)
		ORDER BY 
			ic.INDEX_NAME, ic.COLUMN_POSITION
	`
	return d.gormDB.WithContext(ctx).Raw(query, table, database).Scan(results).Error
}

// queryIndexColumnsViaSysIndexCols 通过系统表查询索引列
func (d *DaMengDriver) queryIndexColumnsViaSysIndexCols(ctx context.Context, database, table string, results *[]indexColumnResult) error {
	query := `
			SELECT 
				i.NAME as index_name, 
				c.NAME as column_name,
				ic.KEYNO as column_position
			FROM SYSCOLUMNS c
			JOIN SYSINDEXES i ON c.ID = i.ID
			JOIN SYSINDEXCOLS ic ON i.ID = ic.ID AND i.INDID = ic.INDID AND c.COLID = ic.COLID
			JOIN SYSOBJECTS o ON c.ID = o.ID
			WHERE o.NAME = UPPER(?)
		`

	args := []interface{}{table}

	if !isCurrentUserSchema(d, database) {
		query += " AND o.SCHEMANAME = UPPER(?)"
		args = append(args, database)
	} else {
		query += " AND o.SCHEMANAME = USER"
	}

	query += " ORDER BY i.NAME, ic.KEYNO"

	return d.gormDB.WithContext(ctx).Raw(query, args...).Scan(results).Error
}

// getPrimaryKeyNames 获取主键约束名称
func (d *DaMengDriver) getPrimaryKeyNames(ctx context.Context, database, table string) map[string]bool {
	primaryKeys := make(map[string]bool)

	type pkResult struct {
		Name string `gorm:"column:name"`
	}

	var pkResults []pkResult
	var query string
	var args []interface{}

	// 根据是否当前用户模式选择查询方式
	if isCurrentUserSchema(d, database) {
		query = `
			SELECT /*+ INDEX(c IDX_USER_CONSTRAINTS) */
				c.CONSTRAINT_NAME as name
			FROM 
				USER_CONSTRAINTS c
			WHERE 
				c.TABLE_NAME = UPPER(?)
				AND c.CONSTRAINT_TYPE = 'P'
		`
		args = []interface{}{table}
	} else {
		query = `
			SELECT /*+ INDEX(c IDX_ALL_CONSTRAINTS) */
				c.CONSTRAINT_NAME as name
			FROM 
				ALL_CONSTRAINTS c
			WHERE 
				c.TABLE_NAME = UPPER(?)
				AND c.OWNER = UPPER(?)
				AND c.CONSTRAINT_TYPE = 'P'
		`
		args = []interface{}{table, database}
	}

	// 执行查询并忽略错误
	d.gormDB.WithContext(ctx).Raw(query, args...).Scan(&pkResults)

	// 将主键约束名添加到映射中
	for _, pk := range pkResults {
		primaryKeys[pk.Name] = true
	}

	return primaryKeys
}

// ExecuteQuery 执行查询SQL
func (d *DaMengDriver) ExecuteQuery(ctx context.Context, query string, args ...interface{}) (*models.QueryResult, error) {
	if !d.IsConnected() {
		return nil, ErrNotConnected
	}

	start := time.Now()
	rows, err := d.gormDB.WithContext(ctx).Raw(query, args...).Rows()
	if err != nil {
		return &models.QueryResult{
			Error:       err.Error(),
			ExecuteTime: time.Since(start),
		}, nil
	}
	defer rows.Close()

	// 获取列名
	columns, err := rows.Columns()
	if err != nil {
		return nil, errors.Wrap(err, "failed to get columns")
	}

	// 获取列类型
	colTypes, err := rows.ColumnTypes()
	if err != nil {
		return nil, errors.Wrap(err, "failed to get column types")
	}

	// 读取数据
	var result []map[string]interface{}
	for rows.Next() {
		values := make([]interface{}, len(columns))
		valuePtrs := make([]interface{}, len(columns))
		for i := range values {
			valuePtrs[i] = &values[i]
		}

		if err := rows.Scan(valuePtrs...); err != nil {
			return nil, errors.Wrap(err, "failed to scan row")
		}

		row := make(map[string]interface{})
		for i, col := range columns {
			val := values[i]

			// 处理特殊类型
			if val != nil {
				// 处理byte数组
				if b, ok := val.([]byte); ok {
					// 尝试确定数据类型
					if colTypes != nil && i < len(colTypes) {
						// 检查数据库列类型
						dbType := strings.ToLower(colTypes[i].DatabaseTypeName())

						// 对于BIGINT类型，转换为字符串以避免JS中的整数溢出
						if strings.Contains(dbType, "bigint") {
							row[col] = string(b)
							continue
						}

						// 对于DECIMAL/NUMERIC/NUMBER类型，也转换为字符串保留精度
						if strings.Contains(dbType, "number") || strings.Contains(dbType, "decimal") {
							row[col] = string(b)
							continue
						}
					}

					// 默认转换为字符串
					row[col] = string(b)
				} else {
					// 检查是否为int64类型，如果是则转换为字符串
					if i64, ok := val.(int64); ok && (i64 > 9007199254740991 || i64 < -9007199254740991) {
						// 超出JavaScript安全整数范围
						row[col] = strconv.FormatInt(i64, 10)
					} else {
						row[col] = val
					}
				}
			} else {
				row[col] = nil
			}
		}
		result = append(result, row)
	}

	return &models.QueryResult{
		Columns:     columns,
		Rows:        result,
		RowCount:    len(result),
		ExecuteTime: time.Since(start),
	}, nil
}

// ExecuteNonQuery 执行非查询SQL
func (d *DaMengDriver) ExecuteNonQuery(ctx context.Context, query string, args ...interface{}) (int64, error) {
	if !d.IsConnected() {
		return 0, ErrNotConnected
	}

	// 检查是否为批量SQL（多个SQL语句以分号分隔）
	statements := splitBatchSQL(query)

	// 如果只有一条语句，直接执行
	if len(statements) == 1 {
		result := d.gormDB.WithContext(ctx).Exec(statements[0], args...)
		if result.Error != nil {
			return 0, errors.Wrap(result.Error, "failed to execute non-query")
		}
		return result.RowsAffected, nil
	}

	// 如果是多条语句，使用事务执行
	tx := d.gormDB.WithContext(ctx).Begin()
	if tx.Error != nil {
		return 0, errors.Wrap(tx.Error, "failed to begin transaction")
	}

	var totalAffected int64

	// 逐条执行SQL语句
	for _, stmt := range statements {
		// 跳过空语句
		stmt = strings.TrimSpace(stmt)
		if stmt == "" {
			continue
		}

		// 跳过注释行
		if strings.HasPrefix(stmt, "--") || strings.HasPrefix(stmt, "/*") {
			continue
		}

		result := tx.Exec(stmt)
		if result.Error != nil {
			tx.Rollback()
			return 0, errors.Wrapf(result.Error, "failed to execute statement: %s", stmt)
		}

		totalAffected += result.RowsAffected
	}

	// 提交事务
	if err := tx.Commit().Error; err != nil {
		return 0, errors.Wrap(err, "failed to commit transaction")
	}

	return totalAffected, nil
}

// splitBatchSQL 拆分批量SQL语句
// 将多个SQL语句（以分号分隔）拆分为单独的语句
func splitBatchSQL(sql string) []string {
	// 使用正则表达式识别SQL分号
	// 这里的实现比较简单，可能无法处理所有复杂情况
	// 比如引号中的分号、多行注释中的分号等

	// 预处理：移除SQL注释
	sql = removeComments(sql)

	var statements []string
	var currentStmt strings.Builder

	// 标记是否在引号内
	inQuote := false
	quoteChar := rune(0)

	for _, char := range sql {
		// 处理引号
		if char == '\'' || char == '"' {
			if !inQuote {
				inQuote = true
				quoteChar = char
			} else if char == quoteChar {
				inQuote = false
			}
		}

		// 添加字符到当前语句
		currentStmt.WriteRune(char)

		// 如果遇到分号且不在引号内，则认为一条语句结束
		if char == ';' && !inQuote {
			stmt := strings.TrimSpace(currentStmt.String())
			if stmt != ";" && stmt != "" {
				statements = append(statements, stmt)
			}
			currentStmt.Reset()
		}
	}

	// 处理最后一条语句（如果没有以分号结尾）
	lastStmt := strings.TrimSpace(currentStmt.String())
	if lastStmt != "" {
		statements = append(statements, lastStmt)
	}

	return statements
}

// removeComments 移除SQL注释
func removeComments(sql string) string {
	// 移除单行注释 (--行注释)
	re := regexp.MustCompile(`--.*?(\r\n|\n|$)`)
	sql = re.ReplaceAllString(sql, "$1")

	// 移除多行注释 (/* ... */)
	re = regexp.MustCompile(`/\*(?s:.*?)\*/`)
	sql = re.ReplaceAllString(sql, " ")

	return sql
}

// BeginTransaction 开始事务
func (d *DaMengDriver) BeginTransaction(ctx context.Context) (DatabaseTransaction, error) {
	if !d.IsConnected() {
		return nil, ErrNotConnected
	}

	tx := d.gormDB.WithContext(ctx).Begin()
	if tx.Error != nil {
		return nil, errors.Wrap(tx.Error, "failed to begin transaction")
	}

	return &DaMengTransaction{tx: tx}, nil
}

// DaMengTransaction 达梦事务实现
type DaMengTransaction struct {
	tx *gorm.DB
}

func (dt *DaMengTransaction) Commit() error {
	return dt.tx.Commit().Error
}

func (dt *DaMengTransaction) Rollback() error {
	return dt.tx.Rollback().Error
}

func (dt *DaMengTransaction) ExecuteQuery(ctx context.Context, query string, args ...interface{}) (*models.QueryResult, error) {
	start := time.Now()
	rows, err := dt.tx.WithContext(ctx).Raw(query, args...).Rows()
	if err != nil {
		return &models.QueryResult{
			Error:       err.Error(),
			ExecuteTime: time.Since(start),
		}, nil
	}
	defer rows.Close()

	columns, err := rows.Columns()
	if err != nil {
		return nil, errors.Wrap(err, "failed to get columns")
	}

	// 获取列类型
	colTypes, err := rows.ColumnTypes()
	if err != nil {
		return nil, errors.Wrap(err, "failed to get column types")
	}

	var result []map[string]interface{}
	for rows.Next() {
		values := make([]interface{}, len(columns))
		valuePtrs := make([]interface{}, len(columns))
		for i := range values {
			valuePtrs[i] = &values[i]
		}

		if err := rows.Scan(valuePtrs...); err != nil {
			return nil, errors.Wrap(err, "failed to scan row")
		}

		row := make(map[string]interface{})
		for i, col := range columns {
			val := values[i]

			// 处理特殊类型
			if val != nil {
				// 处理byte数组
				if b, ok := val.([]byte); ok {
					// 尝试确定数据类型
					if colTypes != nil && i < len(colTypes) {
						// 检查数据库列类型
						dbType := strings.ToLower(colTypes[i].DatabaseTypeName())

						// 对于BIGINT类型，转换为字符串以避免JS中的整数溢出
						if strings.Contains(dbType, "bigint") {
							row[col] = string(b)
							continue
						}

						// 对于DECIMAL/NUMERIC/NUMBER类型，也转换为字符串保留精度
						if strings.Contains(dbType, "number") || strings.Contains(dbType, "decimal") {
							row[col] = string(b)
							continue
						}
					}

					// 默认转换为字符串
					row[col] = string(b)
				} else {
					// 检查是否为int64类型，如果是则转换为字符串
					if i64, ok := val.(int64); ok && (i64 > 9007199254740991 || i64 < -9007199254740991) {
						// 超出JavaScript安全整数范围
						row[col] = strconv.FormatInt(i64, 10)
					} else {
						row[col] = val
					}
				}
			} else {
				row[col] = nil
			}
		}
		result = append(result, row)
	}

	return &models.QueryResult{
		Columns:     columns,
		Rows:        result,
		RowCount:    len(result),
		ExecuteTime: time.Since(start),
	}, nil
}

func (dt *DaMengTransaction) ExecuteNonQuery(ctx context.Context, query string, args ...interface{}) (int64, error) {
	if dt.tx == nil {
		return 0, errors.New("transaction is nil or already committed")
	}

	// 检查是否为批量SQL（多个SQL语句以分号分隔）
	statements := splitBatchSQL(query)

	// 处理批量SQL
	var totalAffected int64

	// 逐条执行SQL语句
	for _, stmt := range statements {
		// 跳过空语句
		stmt = strings.TrimSpace(stmt)
		if stmt == "" {
			continue
		}

		// 跳过注释行
		if strings.HasPrefix(stmt, "--") || strings.HasPrefix(stmt, "/*") {
			continue
		}

		result := dt.tx.WithContext(ctx).Exec(stmt, args...)
		if result.Error != nil {
			return 0, errors.Wrapf(result.Error, "failed to execute statement in transaction: %s", stmt)
		}

		totalAffected += result.RowsAffected
	}

	return totalAffected, nil
}

// Exec 执行SQL命令，返回sql.Result
func (dt *DaMengTransaction) Exec(query string, args ...interface{}) (sql.Result, error) {
	if dt.tx == nil {
		return nil, errors.New("transaction is nil or already committed")
	}

	// 创建一个简单的Result包装器
	result := dt.tx.Exec(query, args...)
	if result.Error != nil {
		return nil, result.Error
	}

	return &gormResult{
		rowsAffected: result.RowsAffected,
	}, nil
}

// gormResult 实现 sql.Result 接口
type gormResult struct {
	rowsAffected int64
	lastInsertID int64
}

func (r *gormResult) LastInsertId() (int64, error) {
	return r.lastInsertID, nil
}

func (r *gormResult) RowsAffected() (int64, error) {
	return r.rowsAffected, nil
}

// Helper function to safely convert *int to int
func intPtrToInt(ptr *int) int {
	if ptr == nil {
		return 0
	}
	return *ptr
}

// isCurrentUserSchema 判断指定的模式是否是当前用户的模式
func isCurrentUserSchema(d *DaMengDriver, database string) bool {
	if database == "" {
		return true
	}

	return strings.ToUpper(database) == strings.ToUpper(d.Config.Username)
}

// CharsetInfo 存储字符集信息
type CharsetInfo struct {
	Name         string // 字符集名称
	BytesPerChar int    // 每个字符占用的最大字节数
}

// getCharsetSemantics 获取达梦数据库当前的字符语义设置和字符集信息
// 返回值：isByteSemantics - 是否字节语义，charsetInfo - 字符集信息
func (d *DaMengDriver) getCharsetSemantics() (bool, *CharsetInfo) {
	// 首先检查缓存是否有效
	if d.charsetInfo != nil && d.isByteSemantics != nil {
		// 检查缓存是否过期（10分钟有效期）
		if !d.charsetCacheTime.IsZero() && time.Since(d.charsetCacheTime) < 10*time.Minute {
			fmt.Printf("[DEBUG] 使用缓存的字符集信息: 字符集=%s, 字节语义=%v, 每字符字节数=%d\n",
				d.charsetInfo.Name, *d.isByteSemantics, d.charsetInfo.BytesPerChar)
			return *d.isByteSemantics, d.charsetInfo
		}
	}

	if !d.IsConnected() {
		// 默认使用字节语义和UTF-8
		byteSemantics := true
		charsetInfo := &CharsetInfo{Name: "UTF8", BytesPerChar: 3}

		// 更新缓存
		d.isByteSemantics = &byteSemantics
		d.charsetInfo = charsetInfo
		d.charsetCacheTime = time.Now()

		return byteSemantics, charsetInfo
	}

	// 记录执行开始时间，用于性能监控
	start := time.Now()
	defer func() {
		fmt.Printf("[DEBUG] 获取字符集信息耗时: %v\n", time.Since(start))
	}()

	// 首先尝试获取当前会话的NLS_LENGTH_SEMANTICS参数
	// 这个参数决定了是字节语义还是字符语义
	var lengthSemantics string
	semanticsQueries := []string{
		// 1. 尝试通过V$PARAMETER视图查询
		`SELECT VALUE FROM V$PARAMETER WHERE NAME = 'NLS_LENGTH_SEMANTICS'`,
		// 2. 尝试通过SESSION_PARAMETERS视图查询
		`SELECT VALUE FROM V$SESSION_PARAMETERS WHERE NAME = 'NLS_LENGTH_SEMANTICS'`,
		// 3. 尝试通过SESSIONPROPERTY函数查询
		`SELECT SESSIONPROPERTY('NLS_LENGTH_SEMANTICS') FROM DUAL`,
		// 4. 尝试通过系统属性查询
		`SELECT SYS_CONTEXT('USERENV', 'NLS_LENGTH_SEMANTICS') FROM DUAL`,
	}

	// 逐个尝试查询语义设置
	var semanticsErr error
	for _, query := range semanticsQueries {
		semanticsErr = d.gormDB.Raw(query).Row().Scan(&lengthSemantics)
		if semanticsErr == nil && lengthSemantics != "" {
			fmt.Printf("[DEBUG] 成功获取字符语义设置: %s, 使用查询: %s\n", lengthSemantics, query)
			break
		}
	}

	// 确定是否使用字节语义
	isByteSemantics := true // 默认字节语义
	if semanticsErr == nil && strings.ToUpper(lengthSemantics) == "CHAR" {
		isByteSemantics = false
	} else {
		// 如果无法确定，尝试查询DaMeng的版本来推断默认设置
		var dmVersion string
		if err := d.gormDB.Raw("SELECT BANNER FROM V$VERSION").Row().Scan(&dmVersion); err == nil {
			fmt.Printf("[DEBUG] 达梦数据库版本: %s\n", dmVersion)
			// DaMeng 8开始默认可能是字符语义
			if strings.Contains(dmVersion, "V8") {
				// 尝试通过其他方式确认
				var semanticsExists int
				checkQuery := `SELECT COUNT(*) FROM V$PARAMETER WHERE NAME = 'NLS_LENGTH_SEMANTICS'`
				if err := d.gormDB.Raw(checkQuery).Row().Scan(&semanticsExists); err == nil && semanticsExists > 0 {
					// 参数存在但无法获取值，保持默认字节语义
					isByteSemantics = true
				}
			}
		}
	}

	// 获取当前数据库字符集
	var charsetName string
	charsetQueries := []string{
		// 1. 通过NLS_PARAMETERS视图查询
		`SELECT VALUE FROM V$NLS_PARAMETERS WHERE PARAMETER = 'NLS_CHARACTERSET'`,
		// 2. 通过SESSION_PARAMETERS视图查询
		`SELECT VALUE FROM V$SESSION_PARAMETERS WHERE PARAMETER = 'NLS_CHARACTERSET'`,
		// 3. 通过SESSIONPROPERTY函数查询
		`SELECT SESSIONPROPERTY('NLS_CHARSET') FROM DUAL`,
		// 4. 通过DATABASE_PROPERTIES视图查询
		`SELECT PROPERTY_VALUE FROM DATABASE_PROPERTIES WHERE PROPERTY_NAME = 'NLS_CHARACTERSET'`,
		// 5. 通过系统环境上下文查询
		`SELECT SYS_CONTEXT('USERENV', 'NLS_CHARSET') FROM DUAL`,
		// 6. 查询当前会话的连接字符集
		`SELECT SESSIONPROPERTY('CONNECTION_CHARSET') FROM DUAL`,
	}

	// 逐个尝试查询字符集
	var charsetErr error
	for _, query := range charsetQueries {
		charsetErr = d.gormDB.Raw(query).Row().Scan(&charsetName)
		if charsetErr == nil && charsetName != "" {
			fmt.Printf("[DEBUG] 成功获取数据库字符集: %s, 使用查询: %s\n", charsetName, query)
			break
		}
	}

	// 如果查询失败，尝试直接从连接参数中获取
	if (charsetErr != nil || charsetName == "") && d.Config != nil && d.Config.Charset != "" {
		charsetName = d.Config.Charset
		fmt.Printf("[DEBUG] 使用配置的字符集: %s\n", charsetName)
	}

	// 如果仍然无法获取，尝试通过测试查询确定编码
	if charsetName == "" {
		charsetName = d.detectCharsetByTest()
		fmt.Printf("[DEBUG] 通过测试检测到字符集: %s\n", charsetName)
	}

	// 如果仍然无法获取，使用默认值UTF8
	if charsetName == "" {
		charsetName = "UTF8"
		fmt.Printf("[DEBUG] 无法检测字符集，使用默认值: %s\n", charsetName)
	}

	// 根据字符集名称确定每个字符占用的最大字节数
	bytesPerChar := getDaMengCharsetBytesPerChar(charsetName)

	// 创建字符集信息对象
	charsetInfo := &CharsetInfo{
		Name:         charsetName,
		BytesPerChar: bytesPerChar,
	}

	fmt.Printf("[DEBUG] 数据库字符集最终结果: 字符集=%s, 字节语义=%v, 每字符字节数=%d\n",
		charsetName, isByteSemantics, bytesPerChar)

	// 更新缓存
	d.isByteSemantics = &isByteSemantics
	d.charsetInfo = charsetInfo
	d.charsetCacheTime = time.Now()

	return isByteSemantics, charsetInfo
}

// detectCharsetByTest 通过测试查询检测字符集
func (d *DaMengDriver) detectCharsetByTest() string {
	// 创建一个测试表并插入特定字符，然后检查存储长度
	// 注意：这只在需要时使用，因为它会创建临时对象

	// 为避免冲突，使用带随机后缀的表名
	randomSuffix := fmt.Sprintf("%d", time.Now().UnixNano()%10000)
	testTableName := "TMP_CHARSET_TEST_" + randomSuffix

	// 确保最后删除测试表
	defer func() {
		d.gormDB.Exec(fmt.Sprintf("DROP TABLE %s", testTableName))
	}()

	// 1. 创建测试表
	createTableSQL := fmt.Sprintf(`CREATE TABLE %s (
		ID INT,
		ASCII_STR VARCHAR(10),
		CJK_STR VARCHAR(10)
	)`, testTableName)

	if err := d.gormDB.Exec(createTableSQL).Error; err != nil {
		fmt.Printf("[DEBUG] 创建字符集测试表失败: %v\n", err)
		return ""
	}

	// 2. 插入测试数据：ASCII字符和中文字符
	insertSQL := fmt.Sprintf(`INSERT INTO %s (ID, ASCII_STR, CJK_STR) VALUES (1, 'abcde', '中文测试')`, testTableName)
	if err := d.gormDB.Exec(insertSQL).Error; err != nil {
		fmt.Printf("[DEBUG] 插入字符集测试数据失败: %v\n", err)
		return ""
	}

	// 3. 查询数据长度
	var asciiLen, cjkLen int
	lengthQuery := fmt.Sprintf(`SELECT 
		LENGTH(ASCII_STR) as ASCII_LEN,
		LENGTH(CJK_STR) as CJK_LEN 
	FROM %s WHERE ID = 1`, testTableName)

	if err := d.gormDB.Raw(lengthQuery).Row().Scan(&asciiLen, &cjkLen); err != nil {
		fmt.Printf("[DEBUG] 查询字符串长度失败: %v\n", err)
		return ""
	}

	// 4. 分析结果推断字符集
	// ASCII字符串"abcde"的长度应该是5
	// 中文字符串"中文测试"的长度取决于编码:
	// - UTF8: 每个中文字符3字节，总共12字节
	// - GBK/GB2312: 每个中文字符2字节，总共8字节
	// - UTF16: 每个中文字符2字节，总共8字节

	fmt.Printf("[DEBUG] 字符集测试结果: ASCII字符串长度=%d, 中文字符串长度=%d\n", asciiLen, cjkLen)

	// 推断字符集
	if asciiLen == 5 {
		// ASCII正常显示为5个字符
		if cjkLen == 4 {
			// 中文显示为4个字符，说明是字符语义
			return "UTF8" // 默认使用UTF8，虽然也可能是其他编码
		} else if cjkLen == 12 {
			// 中文显示为12个字节，说明是UTF8字节语义
			return "UTF8"
		} else if cjkLen == 8 {
			// 中文显示为8个字节，可能是GBK或UTF16
			return "GBK" // 达梦数据库中更可能是GBK
		}
	}

	// 如果无法确定，默认返回UTF8
	return "UTF8"
}

// getDaMengCharsetBytesPerChar 获取达梦数据库字符集的每字符最大字节数
func getDaMengCharsetBytesPerChar(charset string) int {
	// 转换为大写进行比较
	charset = strings.ToUpper(charset)

	// 规范化常见字符集名称的不同写法
	charset = normalizeCharsetName(charset)

	// 根据达梦数据库常见字符集的编码特性
	switch charset {
	case "UTF8", "UTF-8":
		return 3 // UTF-8最多3字节/字符(常见中文)
	case "UTF16", "UTF-16", "AL16UTF16":
		return 2 // UTF-16固定2字节/字符
	case "GBK", "GB2312", "ZHS16GBK":
		return 2 // GBK/GB2312中文通常2字节/字符
	case "GB18030":
		return 4 // GB18030最多4字节/字符
	case "BIG5", "ZHT16BIG5":
		return 2 // Big5通常2字节/字符
	case "ASCII", "US7ASCII":
		return 1 // ASCII固定1字节/字符
	case "LATIN1", "ISO8859-1", "WE8ISO8859P1":
		return 1 // Latin1固定1字节/字符
	default:
		// 对于未知字符集，假设为3字节(保守估计)
		fmt.Printf("[WARN] 未知字符集: %s, 默认使用3字节/字符\n", charset)
		return 3
	}
}

// normalizeCharsetName 规范化字符集名称
func normalizeCharsetName(charset string) string {
	// 处理达梦数据库中字符集名称的多种写法
	// 达梦与Oracle兼容的写法映射
	charsetMap := map[string]string{
		"ZHS16GBK":      "GBK",
		"ZHS32GB18030":  "GB18030",
		"ZHT16BIG5":     "BIG5",
		"ZHT16MSWIN950": "BIG5",
		"AL16UTF16":     "UTF16",
		"AL32UTF8":      "UTF8",
		"US7ASCII":      "ASCII",
		"WE8ISO8859P1":  "LATIN1",
		"WE8ISO8859":    "LATIN1",
		"UTF8MB4":       "UTF8",   // MySQL风格
		"CP936":         "GBK",    // Windows代码页
		"CP950":         "BIG5",   // Windows代码页
		"CP1252":        "LATIN1", // Windows代码页
	}

	if normalized, exists := charsetMap[charset]; exists {
		return normalized
	}

	return charset
}

// collectTableComments 获取表和列的注释信息
func (d *DaMengDriver) collectTableComments(ctx context.Context, database, table string) (map[string]string, error) {
	commentMap := make(map[string]string)

	// 尝试多种方法获取注释
	var methods = []func(context.Context, string, string, map[string]string) error{
		// 方法1: 通过ALL_COL_COMMENTS视图查询（最标准的方法）
		d.getCommentsViaAllColComments,
		// 方法2: 通过USER_COL_COMMENTS视图查询（适用于当前用户权限）
		d.getCommentsViaUserColComments,
		// 方法3: 通过SYS.SYSCOMMENTS系统表查询（某些版本可用）
		d.getCommentsViaSysComments,
		// 方法4: 通过SYS.ALL_COMMENTS视图查询（某些版本可用）
		d.getCommentsViaAllComments,
		// 方法5: 通过SYS.USER_COMMENTS视图查询（某些版本可用）
		d.getCommentsViaUserComments,
		// 方法6: 通过DBA_COL_COMMENTS视图查询（适用于管理员权限）
		d.getCommentsViaDbaColComments,
	}

	// 逐个尝试不同的方法
	for _, method := range methods {
		err := method(ctx, database, table, commentMap)
		if err == nil && len(commentMap) > 0 {
			// 找到了注释，不再继续尝试
			fmt.Printf("[DEBUG] 成功获取到%d个注释\n", len(commentMap))
			return commentMap, nil
		}
	}

	// 如果所有方法都失败，返回空的注释映射
	fmt.Println("[INFO] 无法获取表列注释，可能当前用户无权限或表没有注释")
	return commentMap, nil
}

// getCommentsViaAllColComments 通过ALL_COL_COMMENTS视图获取注释
func (d *DaMengDriver) getCommentsViaAllColComments(ctx context.Context, database, table string, commentMap map[string]string) error {
	query := `
		SELECT 
			COLUMN_NAME, 
			COMMENTS 
		FROM 
			ALL_COL_COMMENTS 
		WHERE 
			TABLE_NAME = UPPER(?) 
			AND OWNER = UPPER(?)
	`
	args := []interface{}{table, database}

	fmt.Println("[DEBUG] 通过ALL_COL_COMMENTS查询注释:", query)

	rows, err := d.DB.QueryContext(ctx, query, args...)
	if err != nil {
		fmt.Println("[ERROR] ALL_COL_COMMENTS查询失败:", err)
		return err
	}
	defer rows.Close()

	count := 0
	for rows.Next() {
		var colName, comments string
		if err := rows.Scan(&colName, &comments); err != nil {
			fmt.Println("[ERROR] 扫描注释数据失败:", err)
			continue
		}

		if comments != "" {
			commentMap[colName] = comments
			count++
		}
	}

	// 单独查询表注释
	tableCommentQuery := `
		SELECT 
			COMMENTS 
		FROM 
			ALL_TAB_COMMENTS 
		WHERE 
			TABLE_NAME = UPPER(?) 
			AND OWNER = UPPER(?)
	`

	var tableComment string
	if err := d.DB.QueryRowContext(ctx, tableCommentQuery, table, database).Scan(&tableComment); err == nil && tableComment != "" {
		commentMap["TABLE"] = tableComment
		count++
	}

	fmt.Printf("[DEBUG] ALL_COL_COMMENTS获取到%d个注释\n", count)
	return nil
}

// getCommentsViaUserColComments 通过USER_COL_COMMENTS视图获取注释
func (d *DaMengDriver) getCommentsViaUserColComments(ctx context.Context, database, table string, commentMap map[string]string) error {
	// 只有当前用户模式才使用USER_视图
	if !isCurrentUserSchema(d, database) {
		return errors.New("not current user schema")
	}

	query := `
		SELECT 
			COLUMN_NAME, 
			COMMENTS 
		FROM 
			USER_COL_COMMENTS 
		WHERE 
			TABLE_NAME = UPPER(?)
	`
	args := []interface{}{table}

	fmt.Println("[DEBUG] 通过USER_COL_COMMENTS查询注释:", query)

	rows, err := d.DB.QueryContext(ctx, query, args...)
	if err != nil {
		fmt.Println("[ERROR] USER_COL_COMMENTS查询失败:", err)
		return err
	}
	defer rows.Close()

	count := 0
	for rows.Next() {
		var colName, comments string
		if err := rows.Scan(&colName, &comments); err != nil {
			fmt.Println("[ERROR] 扫描注释数据失败:", err)
			continue
		}

		if comments != "" {
			commentMap[colName] = comments
			count++
		}
	}

	// 单独查询表注释
	tableCommentQuery := `
		SELECT 
			COMMENTS 
		FROM 
			USER_TAB_COMMENTS 
		WHERE 
			TABLE_NAME = UPPER(?)
	`

	var tableComment string
	if err := d.DB.QueryRowContext(ctx, tableCommentQuery, table).Scan(&tableComment); err == nil && tableComment != "" {
		commentMap["TABLE"] = tableComment
		count++
	}

	fmt.Printf("[DEBUG] USER_COL_COMMENTS获取到%d个注释\n", count)
	return nil
}

// getCommentsViaSysComments 通过SYS.SYSCOMMENTS系统表获取注释
func (d *DaMengDriver) getCommentsViaSysComments(ctx context.Context, database, table string, commentMap map[string]string) error {
	query := `
		SELECT 
			COL_NAME, 
			COMMENTS 
		FROM 
			SYS.SYSCOMMENTS 
		WHERE 
			ID = (SELECT ID FROM SYS.SYSOBJECTS WHERE NAME = UPPER(?))
	`

	args := []interface{}{table}

	if !isCurrentUserSchema(d, database) {
		query = `
			SELECT 
				COL_NAME, 
				COMMENTS 
			FROM 
				SYS.SYSCOMMENTS 
			WHERE 
				ID = (SELECT ID FROM SYS.SYSOBJECTS WHERE NAME = UPPER(?) AND SCHEMANAME = UPPER(?))
		`
		args = []interface{}{table, database}
	}

	fmt.Println("[DEBUG] 通过SYS.SYSCOMMENTS查询注释:", query)

	rows, err := d.DB.QueryContext(ctx, query, args...)
	if err != nil {
		fmt.Println("[ERROR] SYS.SYSCOMMENTS查询失败:", err)
		return err
	}
	defer rows.Close()

	count := 0
	for rows.Next() {
		var colName, comments string
		if err := rows.Scan(&colName, &comments); err != nil {
			fmt.Println("[ERROR] 扫描注释数据失败:", err)
			continue
		}

		if colName == "" {
			// 表注释
			commentMap["TABLE"] = comments
		} else {
			// 列注释
			commentMap[colName] = comments
		}
		count++
	}

	fmt.Printf("[DEBUG] SYS.SYSCOMMENTS获取到%d个注释\n", count)
	return nil
}

// getCommentsViaAllComments 通过SYS.ALL_COMMENTS视图获取注释
func (d *DaMengDriver) getCommentsViaAllComments(ctx context.Context, database, table string, commentMap map[string]string) error {
	// 尝试使用另一种系统视图格式
	query := `
		SELECT 
			COLUMN_NAME, 
			COMMENTS 
		FROM 
			ALL_COMMENTS 
		WHERE 
			TABLE_NAME = UPPER(?) 
			AND OWNER = UPPER(?)
			AND COLUMN_NAME IS NOT NULL
	`
	args := []interface{}{table, database}

	fmt.Println("[DEBUG] 通过ALL_COMMENTS查询注释:", query)

	rows, err := d.DB.QueryContext(ctx, query, args...)
	if err != nil {
		fmt.Println("[ERROR] ALL_COMMENTS查询失败:", err)
		return err
	}
	defer rows.Close()

	count := 0
	for rows.Next() {
		var colName, comments string
		if err := rows.Scan(&colName, &comments); err != nil {
			fmt.Println("[ERROR] 扫描注释数据失败:", err)
			continue
		}

		if comments != "" {
			commentMap[colName] = comments
			count++
		}
	}

	// 单独查询表注释
	tableCommentQuery := `
		SELECT 
			COMMENTS 
		FROM 
			ALL_COMMENTS 
		WHERE 
			TABLE_NAME = UPPER(?) 
			AND OWNER = UPPER(?)
			AND COLUMN_NAME IS NULL
	`

	var tableComment string
	if err := d.DB.QueryRowContext(ctx, tableCommentQuery, table, database).Scan(&tableComment); err == nil && tableComment != "" {
		commentMap["TABLE"] = tableComment
		count++
	}

	fmt.Printf("[DEBUG] ALL_COMMENTS获取到%d个注释\n", count)
	return nil
}

// getCommentsViaUserComments 通过SYS.USER_COMMENTS视图获取注释
func (d *DaMengDriver) getCommentsViaUserComments(ctx context.Context, database, table string, commentMap map[string]string) error {
	// 只有当前用户模式才使用USER_视图
	if !isCurrentUserSchema(d, database) {
		return errors.New("not current user schema")
	}

	// 尝试使用另一种系统视图格式
	query := `
		SELECT 
			COLUMN_NAME, 
			COMMENTS 
		FROM 
			USER_COMMENTS 
		WHERE 
			TABLE_NAME = UPPER(?)
			AND COLUMN_NAME IS NOT NULL
	`
	args := []interface{}{table}

	fmt.Println("[DEBUG] 通过USER_COMMENTS查询注释:", query)

	rows, err := d.DB.QueryContext(ctx, query, args...)
	if err != nil {
		fmt.Println("[ERROR] USER_COMMENTS查询失败:", err)
		return err
	}
	defer rows.Close()

	count := 0
	for rows.Next() {
		var colName, comments string
		if err := rows.Scan(&colName, &comments); err != nil {
			fmt.Println("[ERROR] 扫描注释数据失败:", err)
			continue
		}

		if comments != "" {
			commentMap[colName] = comments
			count++
		}
	}

	// 单独查询表注释
	tableCommentQuery := `
		SELECT 
			COMMENTS 
		FROM 
			USER_COMMENTS 
		WHERE 
			TABLE_NAME = UPPER(?)
			AND COLUMN_NAME IS NULL
	`

	var tableComment string
	if err := d.DB.QueryRowContext(ctx, tableCommentQuery, table).Scan(&tableComment); err == nil && tableComment != "" {
		commentMap["TABLE"] = tableComment
		count++
	}

	fmt.Printf("[DEBUG] USER_COMMENTS获取到%d个注释\n", count)
	return nil
}

// getCommentsViaDbaColComments 通过DBA_COL_COMMENTS视图获取注释
func (d *DaMengDriver) getCommentsViaDbaColComments(ctx context.Context, database, table string, commentMap map[string]string) error {
	query := `
		SELECT 
			COLUMN_NAME, 
			COMMENTS 
		FROM 
			DBA_COL_COMMENTS 
		WHERE 
			TABLE_NAME = UPPER(?) 
			AND OWNER = UPPER(?)
	`
	args := []interface{}{table, database}

	fmt.Println("[DEBUG] 通过DBA_COL_COMMENTS查询注释:", query)

	rows, err := d.DB.QueryContext(ctx, query, args...)
	if err != nil {
		fmt.Println("[ERROR] DBA_COL_COMMENTS查询失败:", err)
		return err
	}
	defer rows.Close()

	count := 0
	for rows.Next() {
		var colName, comments string
		if err := rows.Scan(&colName, &comments); err != nil {
			fmt.Println("[ERROR] 扫描注释数据失败:", err)
			continue
		}

		if comments != "" {
			commentMap[colName] = comments
			count++
		}
	}

	// 单独查询表注释
	tableCommentQuery := `
		SELECT 
			COMMENTS 
		FROM 
			DBA_TAB_COMMENTS 
		WHERE 
			TABLE_NAME = UPPER(?) 
			AND OWNER = UPPER(?)
	`

	var tableComment string
	if err := d.DB.QueryRowContext(ctx, tableCommentQuery, table, database).Scan(&tableComment); err == nil && tableComment != "" {
		commentMap["TABLE"] = tableComment
		count++
	}

	fmt.Printf("[DEBUG] DBA_COL_COMMENTS获取到%d个注释\n", count)
	return nil
}

// collectDefaultValues 获取列的默认值
func (d *DaMengDriver) collectDefaultValues(ctx context.Context, database, table string) (map[string]string, error) {
	defaultMap := make(map[string]string)

	// 尝试多种方法获取默认值
	var methods = []func(context.Context, string, string, map[string]string) error{
		// 方法1: 通过ALL_TAB_COLUMNS视图查询（最标准的方法）
		d.getDefaultsViaAllTabColumns,
		// 方法2: 通过USER_TAB_COLUMNS视图查询（适用于当前用户权限）
		d.getDefaultsViaUserTabColumns,
		// 方法3: 通过SYS.SYSCOLUMNS和SYS.SYSAUTOGEN系统表查询（某些版本可用）
		d.getDefaultsViaSysColumns,
		// 方法4: 通过ALL_TAB_COLS视图查询（某些版本可用）
		d.getDefaultsViaAllTabCols,
		// 方法5: 通过DBA_TAB_COLUMNS视图查询（适用于管理员权限）
		d.getDefaultsViaDbaTabColumns,
	}

	// 逐个尝试不同的方法
	for _, method := range methods {
		err := method(ctx, database, table, defaultMap)
		if err == nil && len(defaultMap) > 0 {
			// 找到了默认值，不再继续尝试
			fmt.Printf("[DEBUG] 成功获取到%d个默认值\n", len(defaultMap))
			return defaultMap, nil
		}
	}

	// 如果所有方法都失败，返回空的默认值映射
	fmt.Println("[INFO] 无法获取表列默认值，可能当前用户无权限或表没有默认值")
	return defaultMap, nil
}

// getDefaultsViaAllTabColumns 通过ALL_TAB_COLUMNS视图获取默认值
func (d *DaMengDriver) getDefaultsViaAllTabColumns(ctx context.Context, database, table string, defaultMap map[string]string) error {
	query := `
		SELECT 
			COLUMN_NAME, 
			NVL(DATA_DEFAULT, '') as DATA_DEFAULT
		FROM 
			ALL_TAB_COLUMNS 
		WHERE 
			TABLE_NAME = UPPER(?) 
			AND OWNER = UPPER(?)
	`
	args := []interface{}{table, database}

	fmt.Println("[DEBUG] 通过ALL_TAB_COLUMNS查询默认值:", query)

	rows, err := d.DB.QueryContext(ctx, query, args...)
	if err != nil {
		fmt.Println("[ERROR] ALL_TAB_COLUMNS查询失败:", err)
		return err
	}
	defer rows.Close()

	count := 0
	for rows.Next() {
		var colName, defaultValue string
		if err := rows.Scan(&colName, &defaultValue); err != nil {
			fmt.Println("[ERROR] 扫描默认值数据失败:", err)
			continue
		}

		// 处理默认值
		defaultValue = cleanDefaultValue(defaultValue)
		if defaultValue != "" {
			defaultMap[colName] = defaultValue
			count++
		}
	}

	fmt.Printf("[DEBUG] ALL_TAB_COLUMNS获取到%d个默认值\n", count)
	return nil
}

// getDefaultsViaUserTabColumns 通过USER_TAB_COLUMNS视图获取默认值
func (d *DaMengDriver) getDefaultsViaUserTabColumns(ctx context.Context, database, table string, defaultMap map[string]string) error {
	// 只有当前用户模式才使用USER_视图
	if !isCurrentUserSchema(d, database) {
		return errors.New("not current user schema")
	}

	query := `
		SELECT 
			COLUMN_NAME, 
			NVL(DATA_DEFAULT, '') as DATA_DEFAULT
		FROM 
			USER_TAB_COLUMNS 
		WHERE 
			TABLE_NAME = UPPER(?)
	`
	args := []interface{}{table}

	fmt.Println("[DEBUG] 通过USER_TAB_COLUMNS查询默认值:", query)

	rows, err := d.DB.QueryContext(ctx, query, args...)
	if err != nil {
		fmt.Println("[ERROR] USER_TAB_COLUMNS查询失败:", err)
		return err
	}
	defer rows.Close()

	count := 0
	for rows.Next() {
		var colName, defaultValue string
		if err := rows.Scan(&colName, &defaultValue); err != nil {
			fmt.Println("[ERROR] 扫描默认值数据失败:", err)
			continue
		}

		// 处理默认值
		defaultValue = cleanDefaultValue(defaultValue)
		if defaultValue != "" {
			defaultMap[colName] = defaultValue
			count++
		}
	}

	fmt.Printf("[DEBUG] USER_TAB_COLUMNS获取到%d个默认值\n", count)
	return nil
}

// getDefaultsViaSysColumns 通过SYS.SYSCOLUMNS和SYS.SYSAUTOGEN系统表获取默认值
func (d *DaMengDriver) getDefaultsViaSysColumns(ctx context.Context, database, table string, defaultMap map[string]string) error {
	// 查询默认值的SQL - 尝试使用系统表
	query := `
		SELECT 
			c.NAME as COLUMN_NAME, 
			COALESCE(a.DEFOBJNAME, '') as DEFAULT_VALUE 
		FROM 
			SYS.SYSCOLUMNS c
		LEFT JOIN 
			SYS.SYSAUTOGEN a ON c.ID = a.ID AND c.COLID = a.COLID
		WHERE 
			c.ID = (SELECT ID FROM SYS.SYSOBJECTS WHERE NAME = UPPER(?))
	`

	args := []interface{}{table}

	if !isCurrentUserSchema(d, database) {
		query = `
			SELECT 
				c.NAME as COLUMN_NAME, 
				COALESCE(a.DEFOBJNAME, '') as DEFAULT_VALUE 
			FROM 
				SYS.SYSCOLUMNS c
			LEFT JOIN 
				SYS.SYSAUTOGEN a ON c.ID = a.ID AND c.COLID = a.COLID
			WHERE 
				c.ID = (SELECT ID FROM SYS.SYSOBJECTS WHERE NAME = UPPER(?) AND SCHEMANAME = UPPER(?))
		`
		args = []interface{}{table, database}
	}

	fmt.Println("[DEBUG] 通过SYS.SYSCOLUMNS查询默认值:", query)

	rows, err := d.DB.QueryContext(ctx, query, args...)
	if err != nil {
		fmt.Println("[ERROR] SYS.SYSCOLUMNS查询失败:", err)
		return err
	}
	defer rows.Close()

	count := 0
	for rows.Next() {
		var colName, defaultValue string
		if err := rows.Scan(&colName, &defaultValue); err != nil {
			fmt.Println("[ERROR] 扫描默认值数据失败:", err)
			continue
		}

		// 处理默认值
		defaultValue = cleanDefaultValue(defaultValue)
		if defaultValue != "" {
			defaultMap[colName] = defaultValue
			count++
		}
	}

	fmt.Printf("[DEBUG] SYS.SYSCOLUMNS获取到%d个默认值\n", count)
	return nil
}

// getDefaultsViaAllTabCols 通过ALL_TAB_COLS视图获取默认值
func (d *DaMengDriver) getDefaultsViaAllTabCols(ctx context.Context, database, table string, defaultMap map[string]string) error {
	query := `
		SELECT 
			COLUMN_NAME, 
			NVL(DATA_DEFAULT, '') as DATA_DEFAULT
		FROM 
			ALL_TAB_COLS 
		WHERE 
			TABLE_NAME = UPPER(?) 
			AND OWNER = UPPER(?)
	`
	args := []interface{}{table, database}

	fmt.Println("[DEBUG] 通过ALL_TAB_COLS查询默认值:", query)

	rows, err := d.DB.QueryContext(ctx, query, args...)
	if err != nil {
		fmt.Println("[ERROR] ALL_TAB_COLS查询失败:", err)
		return err
	}
	defer rows.Close()

	count := 0
	for rows.Next() {
		var colName, defaultValue string
		if err := rows.Scan(&colName, &defaultValue); err != nil {
			fmt.Println("[ERROR] 扫描默认值数据失败:", err)
			continue
		}

		// 处理默认值
		defaultValue = cleanDefaultValue(defaultValue)
		if defaultValue != "" {
			defaultMap[colName] = defaultValue
			count++
		}
	}

	fmt.Printf("[DEBUG] ALL_TAB_COLS获取到%d个默认值\n", count)
	return nil
}

// getDefaultsViaDbaTabColumns 通过DBA_TAB_COLUMNS视图获取默认值
func (d *DaMengDriver) getDefaultsViaDbaTabColumns(ctx context.Context, database, table string, defaultMap map[string]string) error {
	query := `
		SELECT 
			COLUMN_NAME, 
			NVL(DATA_DEFAULT, '') as DATA_DEFAULT
		FROM 
			DBA_TAB_COLUMNS 
		WHERE 
			TABLE_NAME = UPPER(?) 
			AND OWNER = UPPER(?)
	`
	args := []interface{}{table, database}

	fmt.Println("[DEBUG] 通过DBA_TAB_COLUMNS查询默认值:", query)

	rows, err := d.DB.QueryContext(ctx, query, args...)
	if err != nil {
		fmt.Println("[ERROR] DBA_TAB_COLUMNS查询失败:", err)
		return err
	}
	defer rows.Close()

	count := 0
	for rows.Next() {
		var colName, defaultValue string
		if err := rows.Scan(&colName, &defaultValue); err != nil {
			fmt.Println("[ERROR] 扫描默认值数据失败:", err)
			continue
		}

		// 处理默认值
		defaultValue = cleanDefaultValue(defaultValue)
		if defaultValue != "" {
			defaultMap[colName] = defaultValue
			count++
		}
	}

	fmt.Printf("[DEBUG] DBA_TAB_COLUMNS获取到%d个默认值\n", count)
	return nil
}

// cleanDefaultValue 清理和格式化默认值
func cleanDefaultValue(defaultValue string) string {
	// 清理默认值
	defaultValue = strings.TrimSpace(defaultValue)
	if defaultValue == "" || defaultValue == "<nil>" {
		return ""
	}

	// 达梦数据库常常在默认值上添加额外的引号，需要去除
	if strings.HasPrefix(defaultValue, "'") && strings.HasSuffix(defaultValue, "'") {
		defaultValue = defaultValue[1 : len(defaultValue)-1]
	}

	// 特殊处理一些特定的默认值
	upperDefaultValue := strings.ToUpper(defaultValue)
	if upperDefaultValue == "SYSDATE" || upperDefaultValue == "SYSTIMESTAMP" {
		// 保持原样，这些是达梦的系统函数
		return upperDefaultValue
	} else if strings.Contains(strings.ToLower(defaultValue), "current_timestamp") {
		// 格式化为标准形式
		return "CURRENT_TIMESTAMP"
	}

	return defaultValue
}

// GenerateAlterTableSQL 生成修改表SQL
func (d *DaMengDriver) GenerateAlterTableSQL(database, table string, alterSchema *models.TableAlterSchema) ([]string, error) {
	sqls := []string{}
	tableName := d.formatTableIdentifier(database, table)

	// 处理列操作
	if len(alterSchema.DropColumns) > 0 {
		for _, col := range alterSchema.DropColumns {
			sql := fmt.Sprintf("ALTER TABLE %s DROP COLUMN %s", tableName, d.Dialect.QuoteIdentifier(col))
			sqls = append(sqls, sql)
		}
	}

	if len(alterSchema.AddColumns) > 0 {
		for _, col := range alterSchema.AddColumns {
			colDef := d.generateColumnDefinition(col)
			sql := fmt.Sprintf("ALTER TABLE %s ADD %s", tableName, colDef)
			sqls = append(sqls, sql)
		}
	}

	if len(alterSchema.ModifyColumns) > 0 {
		for _, col := range alterSchema.ModifyColumns {
			colDef := d.generateColumnDefinition(col)
			sql := fmt.Sprintf("ALTER TABLE %s MODIFY %s", tableName, colDef)
			sqls = append(sqls, sql)
		}
	}

	if len(alterSchema.RenameColumns) > 0 {
		for oldName, newName := range alterSchema.RenameColumns {
			sql := fmt.Sprintf("ALTER TABLE %s RENAME COLUMN %s TO %s",
				tableName,
				d.Dialect.QuoteIdentifier(oldName),
				d.Dialect.QuoteIdentifier(newName))
			sqls = append(sqls, sql)
		}
	}

	// 处理索引操作
	if len(alterSchema.DropIndexes) > 0 {
		for _, idx := range alterSchema.DropIndexes {
			sql := fmt.Sprintf("DROP INDEX %s", d.Dialect.QuoteIdentifier(idx))
			sqls = append(sqls, sql)
		}
	}

	if len(alterSchema.AddIndexes) > 0 {
		for _, idx := range alterSchema.AddIndexes {
			// 使用直接的字符串拼接，不再生成未使用的indexDef变量
			sql := fmt.Sprintf("CREATE %s %s ON %s (%s)",
				d.getIndexTypeClause(idx.Type),
				d.Dialect.QuoteIdentifier(idx.Name),
				tableName,
				d.getIndexColumnsClause(idx.Columns))
			sqls = append(sqls, sql)
		}
	}

	// 处理外键操作（达梦支持外键）
	if len(alterSchema.DropForeignKeys) > 0 {
		for _, fk := range alterSchema.DropForeignKeys {
			sql := fmt.Sprintf("ALTER TABLE %s DROP CONSTRAINT %s", tableName, d.Dialect.QuoteIdentifier(fk))
			sqls = append(sqls, sql)
		}
	}

	if len(alterSchema.AddForeignKeys) > 0 {
		for _, fk := range alterSchema.AddForeignKeys {
			fkDef := d.generateForeignKeyDefinition(fk)
			sql := fmt.Sprintf("ALTER TABLE %s ADD %s", tableName, fkDef)
			sqls = append(sqls, sql)
		}
	}

	// 处理表注释
	if alterSchema.Comment != "" {
		sql := fmt.Sprintf("COMMENT ON TABLE %s IS %s", tableName, d.Dialect.QuoteString(alterSchema.Comment))
		sqls = append(sqls, sql)
	}

	return sqls, nil
}

// formatTableIdentifier 格式化表标识符
func (d *DaMengDriver) formatTableIdentifier(database, table string) string {
	if database == "" {
		return d.Dialect.QuoteIdentifier(table)
	}
	return d.Dialect.QuoteIdentifier(database) + "." + d.Dialect.QuoteIdentifier(table)
}

// generateColumnDefinition 生成列定义
func (d *DaMengDriver) generateColumnDefinition(col models.ColumnSchema) string {
	var def strings.Builder

	def.WriteString(d.Dialect.QuoteIdentifier(col.Name))
	def.WriteString(" ")
	def.WriteString(col.Type)

	// 长度/精度
	if col.Length > 0 {
		if col.Scale > 0 {
			def.WriteString(fmt.Sprintf("(%d,%d)", col.Length, col.Scale))
		} else {
			def.WriteString(fmt.Sprintf("(%d)", col.Length))
		}
	}

	// 是否可为空
	if col.NotNull {
		def.WriteString(" NOT NULL")
	} else {
		def.WriteString(" NULL")
	}

	// 默认值
	if col.DefaultValue != "" {
		if col.DefaultValue == "CURRENT_TIMESTAMP" ||
			col.DefaultValue == "SYSDATE" ||
			col.DefaultValue == "SYSTIMESTAMP" {
			def.WriteString(" DEFAULT " + col.DefaultValue)
		} else {
			def.WriteString(" DEFAULT " + d.Dialect.QuoteString(col.DefaultValue))
		}
	}

	// 自增（达梦使用IDENTITY）
	if col.AutoIncrement {
		def.WriteString(" IDENTITY")
	}

	return def.String()
}

// 获取索引类型子句
func (d *DaMengDriver) getIndexTypeClause(indexType string) string {
	indexType = strings.ToUpper(indexType)
	if indexType == "UNIQUE" {
		return "UNIQUE INDEX"
	} else if indexType == "FULLTEXT" {
		return "TEXT INDEX" // 达梦的文本索引
	} else {
		return "INDEX"
	}
}

// 获取索引列子句
func (d *DaMengDriver) getIndexColumnsClause(columns []string) string {
	quotedCols := make([]string, len(columns))
	for i, col := range columns {
		quotedCols[i] = d.Dialect.QuoteIdentifier(col)
	}
	return strings.Join(quotedCols, ", ")
}

// generateIndexDefinition 生成索引定义
func (d *DaMengDriver) generateIndexDefinition(idx models.IndexSchema) string {
	var def strings.Builder

	if strings.ToUpper(idx.Type) == "UNIQUE" {
		def.WriteString("UNIQUE INDEX ")
	} else if strings.ToUpper(idx.Type) == "FULLTEXT" {
		def.WriteString("TEXT INDEX ")
	} else {
		def.WriteString("INDEX ")
	}

	def.WriteString(d.Dialect.QuoteIdentifier(idx.Name))
	def.WriteString(" (")

	quotedCols := make([]string, len(idx.Columns))
	for i, col := range idx.Columns {
		quotedCols[i] = d.Dialect.QuoteIdentifier(col)
	}
	def.WriteString(strings.Join(quotedCols, ", "))
	def.WriteString(")")

	return def.String()
}

// generateForeignKeyDefinition 生成外键定义
func (d *DaMengDriver) generateForeignKeyDefinition(fk models.ForeignKeySchema) string {
	var def strings.Builder

	def.WriteString("CONSTRAINT ")
	def.WriteString(d.Dialect.QuoteIdentifier(fk.Name))
	def.WriteString(" FOREIGN KEY (")

	quotedCols := make([]string, len(fk.Columns))
	for i, col := range fk.Columns {
		quotedCols[i] = d.Dialect.QuoteIdentifier(col)
	}
	def.WriteString(strings.Join(quotedCols, ", "))
	def.WriteString(") REFERENCES ")

	def.WriteString(d.Dialect.QuoteIdentifier(fk.ReferenceTable))
	def.WriteString(" (")

	quotedRefCols := make([]string, len(fk.ReferenceColumns))
	for i, col := range fk.ReferenceColumns {
		quotedRefCols[i] = d.Dialect.QuoteIdentifier(col)
	}
	def.WriteString(strings.Join(quotedRefCols, ", "))
	def.WriteString(")")

	if fk.UpdateRule != "" {
		def.WriteString(" ON UPDATE " + fk.UpdateRule)
	}
	if fk.DeleteRule != "" {
		def.WriteString(" ON DELETE " + fk.DeleteRule)
	}

	return def.String()
}
